Understanding PDF Creation in Python

Asked 2 years ago, Updated 2 years ago, 27 views

I am using PyQt to create a PDF from an HTML file.
There is an error and it doesn't work
I can create a PDF, but I'm having trouble with just a white PDF inside.

The error code is
__agent_connection_block_invoke_2: Connection error-Connection invalid

I don't know what to do when it comes out like this, so please let me know

Python 2.7.10 uses PyQt4
Here's the code.

#coding utf-8
import markdown
import sys
importos
from PyQt4.QtCore import QUrl
from PyQt4.QtGui import QApplication, QPrinter
from PyQt4.QtWebKit import QWebView

app=QApplication(sys.argv)
web=QWebView()
printer=QPrinter()

defload_finished():
    global web
    global printer

    web.print_(printer)
    QApplication.exit()

defmd2html(_fileName):
    md = markdown.Markdown()
    text=""
    for i in open(_fileName, "r"):
         text+=i
    text=md.convert(text)

    fn=open("test.html", "w")
    fn.write(text)
    fn.close()

defhtml2pdf():
    global app
    printer.setOutputFormat (QPrinter.PdfFormat)
    printer.setOrientation(QPrinter.Landscape)
    printer.setPageSize(QPrinter.A4)
    printer.setResolution (QPrinter.HighResolution)
    printer.setOutputFileName('test.pdf')

    web.loadFinished.connect(load_finished)
    web.load(QUrl.fromLocalFile(os.path.join(os.path.dirname(__file__), 'test.html'))))

    sys.exit(app.exec_())




md2html ("aaa.md")
html2pdf()

python

2022-09-30 21:09

1 Answers

of the following codes:

web.load(QUrl.fromLocalFile(os.path.join(os.path.dirname(__file__), 'test.html'))))

The file path specified in QUrl.fromLocalFile must be an absolute path.This is because it internally translates to the format file://....In fact, os.path.join(os.path.dirname(__file__), 'test.html') will be test.html (relative path).

Therefore, here we are:

web.load(QUrl.fromLocalFile(os.path.abspath('test.html'))))

Also, md.convert() does not add an HTML header, so the UTF-8 string will not be handled correctly (so-called garbled characters occur).Therefore, add the Content-Type.

text=md.convert(text)
fn=open("test.html", "w")
=>
text='<html><head><meta http-equiv="Content-Type" content="text/html;charset=UTF-8">>/head>>'+md.convert(text)+'<gt;gt;>>gt;> body>>>>>
fn=open("test.html", "w")

もっとThere may be a better way.


2022-09-30 21:09

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.