Heim  >  Fragen und Antworten  >  Hauptteil

Konvertieren Sie HTML-Dateien mit WeasyPrint in PDF

Ich habe viele HTML-Dateien und möchte sie als lokale PDF-Dateien speichern

Also habe ich versucht, weasyprint zum Konvertieren zu verwenden, aber es gelang mir nicht

Kann mir jemand beim Schreiben des Codes helfen?

def pdf_generate():
    try:

        pdf_file = HTML(string='56129.html').write_pdf()
        with open("my_pdf_file.pdf", 'wb') as f:
            f.write(pdf_file)

    except Exception as e:
        print(str(e))
        return None

Ich habe die HTML-Datei lokal und möchte die PDF-Datei auch lokal speichern

Ich habe die Antwort umgesetzt

def pdf_generate():
    try:
        #将'56129.html'替换为你的HTML文件的路径
        html_file_path = 'farm_management/scripts/56129.html'

        html = HTML(filename=html_file_path)

        pdf_file_path = 'my_pdf_file.pdf'

        pdf_file = html.write_pdf(pdf_file_path)
        with open("my_pdf_file.pdf", 'wb') as f:
            f.write(pdf_file)

        print(f'PDF文件已写入至:{pdf_file_path}')

    except Exception as e:
        print(str(e))

Und der folgende Fehler ist aufgetreten

需要一个类似字节的对象,而不是'NoneType'

P粉729198207P粉729198207403 Tage vor549

Antworte allen(1)Ich werde antworten

  • P粉384679266

    P粉3846792662023-09-12 13:53:44

    如果您的HTML文件是一个字符串,您应该使用HTML(string=html_string).write_pdf()方法。

    但是,如果它是您本地目录中的一个文件,您应该使用HTML(filename=html_file_path).write_pdf()方法。

    代码如下:

    from weasyprint import HTML
    
    def pdf_generate():
        try:
            # 将'56129.html'替换为您的HTML文件的路径
            html_file_path = '56129.html'
    
            html = HTML(filename=html_file_path)
    
            pdf_file_path = 'my_pdf_file.pdf'
    
            html.write_pdf(pdf_file_path)
    
            print(f'PDF文件已写入:{pdf_file_path}')
    
        except Exception as e:
            print(str(e))
    
    pdf_generate()

    Antwort
    0
  • StornierenAntwort