Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

98
Views
PyPDF2 decoding issue when adding annotations in Chinese characters with addJS

I want to use PyPDF2 to add annotations programmatically with the use of addJS, it works very well for Latins characters but not for Chinese character, tried to encode with UTF-8 but seems not work either. Here are the code:

from PyPDF2 import PdfFileWriter, PdfFileReader
Def Test():
    inputPDF = PdfFileReader('./demo/TESTPDFANNOTATION.pdf', "rb")    
    outputPDF = PdfFileWriter()
       
    pages = inputPDF.getNumPages()
    for p in range(pages):
        outputPDF.addPage(inputPDF.getPage(p))

    outputStream = open('./demo/TESTPDFANNOTATIONOUT.pdf', "wb")
    outputPDF.addJS("var annot = this.addAnnot({ \r \
                    page: 0, \r \
                    type: 'FreeText', \r \
                    contents: '你好', \r \
                    textFont: 'csongl', \r \
                    textSize: 10, \r \
                    rect: [200, 300, 200+150, 300+3*12], // height for three lines \r \
                    width: 1, \r \
                    alignment: 1 \r \
                    });")
    outputPDF.write(outputStream)    
    outputStream.close()
    return("ok")

It's weird that If I opened the PDF in notepad text editor, the Chinese characters displayed correctly however when opened with PDF, it shows something like 佀好, which seems not decoded, since they could be decoded with the online convert tool into almost the right Chinese character, not exactly the same for some cases. https://cafewebmaster.com/online_tools/utf_decode

Any advise would be highly appreciated!

Python version: 3.9+ OS: Win10

Thanks Stanley

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Finally, figured out to use another package PyMuPDF to add annotations programmatically with good support of Chinese characters.

import fitz

def writeAnnotation():
    blue  = (0,0,1)
    gold  = (1,1,0)

    pdfDoc = fitz.open('./demo/TESTPDFANNOTATION.pdf')
    page = pdfDoc[0]

    rect1 = fitz.Rect(100,100,200,150)

    strContent1= "你好!世界"

    a1 = page.addFreetextAnnot(rect1, strContent1, text_color=blue,  fill_color=gold)

    pdfDoc.save("./demo/TESTPDFANNOTATIONOUT.pdf")
    return("Well done!")
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!