Python Forum
How can I write formatted (i.e. bold, italic, change font size, etc.) text to a file?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How can I write formatted (i.e. bold, italic, change font size, etc.) text to a file?
#1
Hello all. I'm wondering if someone can direct me to the proper documentation for how to write text to a file that is formatted in different ways, such as making the font bold or italicized, or changing the font sizes, etc. Ideally it would be a .doc file.

Thank you!
John
Reply
#2
https://python-docx.readthedocs.io/en/latest/
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
(Jun-19-2018, 04:33 AM)buran Wrote: https://python-docx.readthedocs.io/en/latest/

Thanks very much! Just two quick questions: is there no built-in way to do these things? And, do you know if this works with .doc (not .docx) files?

The documentation says:

Quote:You can open any Word 2007 or later file this way (.doc files from Word 2003 and earlier won’t work).

But I'm not sure if this means .doc files will work at all. Not sure when they got replaced by .docx. Maybe it was 2003.

Thanks!
Reply
#4
(Jun-19-2018, 04:41 AM)JohnJSal Wrote: is there no built-in way to do these things?
This is the python way. I guess you refer to Standard Python Library. It is the core, there are thousands of third-party packages available through PyPi. And yet others that are not on PyPI.

(Jun-19-2018, 04:41 AM)JohnJSal Wrote: do you know if this works with .doc (not .docx) files
No, it's just for docx files. doc and docx are different formats. For doc files you will need to use pywin32 - Python extensions for Windows. It provides access to much of the Win32 API, the ability to create and use COM objects, and the Pythonwin environment.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#5
(Jun-19-2018, 05:57 AM)buran Wrote:
(Jun-19-2018, 04:41 AM)JohnJSal Wrote: is there no built-in way to do these things?
This is the python way. I guess you refer to Standard Python Library. It is the core, there are thousands of third-party packages available through PyPi. And yet others that are not on PyPI.

Oh, so this is already installed? It looked like I had to install it myself through pip. Either way, I will give it a try.

Thanks!
Reply
#6
(Jun-19-2018, 02:41 PM)JohnJSal Wrote: Oh, so this is already installed?
Exactly the opposite. Python Standard Library provides core functionality and python-docx is one of the third-party packages on PyPI that extend the core functionality. You need to install it via pip.
Now there are some python distributions that have some external modules pre-installed, but I refer to pure python distribution, available at python.org
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#7
Thanks!
Reply
#8
To write formatted text (such as bold, italic, or changing font sizes) to a file in Python, you can use libraries like python-docx for creating and editing .docx files. Here's a simple example of how you can create a document with formatted text:

from docx import Document
from docx.shared import Pt

# Create a new Document
doc = Document()

# Add a paragraph with formatted text
para = doc.add_paragraph()

# Add text with bold and italic formatting
para.add_run('This text is bold and italicized.').bold = True
para.add_run(' This part is italicized.').italic = True

# Add a larger font size
run = para.add_run(' This text has a larger font size.')
run.font.size = Pt(14)

# Save the document
doc.save('formatted_text.docx')
This script will create a .docx file where some text is bold, some italicized, and other parts have a larger font size.

For further customization, you can refer to the python-docx documentation, where you'll find more options for formatting your text.

Additionally, if you’re interested in making your file or profile more stylis, you can use stylishname to generate unique and creative names or fonts for your online profiles, including game usernames.
Gribouillis write Jan-19-2025, 09:00 AM:
Clickbait link removed. Please read What to NOT include in a post
Reply
#9
If you are happy with PDFs, you can use reportlab and have absolute and minute control over every aspect of formatting.

Read the reportlab_userguide.pdf, especially from page 72.

Here a small example of the almost endless possibilities:

from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import A4
from reportlab.lib.colors import pink, green, brown, white, black
from reportlab.lib.styles import ParagraphStyle
from reportlab.lib.styles import getSampleStyleSheet

path2sizes_pdf = 'reportlab/pdfs/text_sizes.pdf'
stylesheet=getSampleStyleSheet()

c = canvas.Canvas(path2sizes_pdf, pagesize=A4)

def fonts(canvas):
    from reportlab.lib.units import inch
    text = "Now is the time for all good men to..."
    x = 3 * inch
    y = 8 * inch
    size = 13
    for font in canvas.getAvailableFonts():
        canvas.setFont(font, size)
        canvas.drawString(x,y,text)
        canvas.setFont("Helvetica", size)
        canvas.drawRightString(x,y, font+":")
        y = y-size
        size = size + 1

fonts(c)
c.showPage() # closes the page, can't add more to this page
c.save()

path2colour_pdf = 'reportlab/pdfs/text_colours.pdf'
mycolours = [pink, green, brown, white, black]

def colours(canvas):
    from reportlab.lib.units import inch
    text = "Now is the time for all good men to..."
    x = 2 * inch
    y = 8 * inch
    for colour in mycolours:
        canvas.setFont("Helvetica", 14)
        c.setFillColor(colour)
        canvas.drawString(x,y,text)
        y = y-15

colours(c)
c.showPage() # closes the page, can't add more to this page
c.save()    
You can direct reportlab to any font you like and then use that font.

from reportlab.pdfbase import pdfmetrics

# important for getting a Chinese ttf
fontpath = '/home/pedro/.local/share/fonts/'
ttfFile = os.path.join(fontpath, '萌萌哒情根深种-中文.ttf')
pdfmetrics.registerFont(TTFont("Chinese", ttfFile))
Reply
#10
This script creates a simple .docx file with some bold and italic text:

import { Document, Paragraph, TextRun } from "docx";
import { writeFileSync } from "fs";

// Create document
const doc = new Document({
  sections: [{
    properties: {},
    children: [
      new Paragraph({
        children: [
          new TextRun({
            text: "Hello World",
            bold: true,
          }),
          new TextRun({
            text: " This is a new paragraph.",
            italics: true,
          }),
        ],
      }),
    ],
  }],
});

// Used to export the file into a .docx file
const buffer = await Packer.toBuffer(doc);

// Write the file
writeFileSync("My Document.docx", buffer);

console.log("Document created successfully");
Gribouillis write Jan-19-2025, 09:30 AM:
Please post all code, output and errors (it it's entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
our gd project- geometry dash
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to write variable in a python file then import it in another python file? tatahuft 4 829 Jan-01-2025, 12:18 AM
Last Post: Skaperen
  [SOLVED] [Linux] Write file and change owner? Winfried 6 1,421 Oct-17-2024, 01:15 AM
Last Post: Winfried
  Print text with big font and style tomtom 6 20,224 Aug-13-2024, 07:26 AM
Last Post: yazistilleriio
  What does .flush do? How can I change this to write to the file? Pedroski55 3 1,265 Apr-22-2024, 01:15 PM
Last Post: snippsat
  Last record in file doesn't write to newline gonksoup 3 1,481 Jan-22-2024, 12:56 PM
Last Post: deanhystad
  Python code for alignment and font size 1418 0 905 Jan-14-2024, 03:56 AM
Last Post: 1418
  write to csv file problem jacksfrustration 11 4,703 Nov-09-2023, 01:56 PM
Last Post: deanhystad
  python Read each xlsx file and write it into csv with pipe delimiter mg24 4 3,678 Nov-09-2023, 10:56 AM
Last Post: mg24
  logging: change log file permission with RotatingFileHandler erg 0 2,403 Aug-09-2023, 01:24 PM
Last Post: erg
  How can I change the uuid name of a file to his original file? MaddoxMB 2 2,041 Jul-17-2023, 10:15 PM
Last Post: Pedroski55

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020