【问题标题】:pdfkit create pages using from_stringpdfkit 使用 from_string 创建页面
【发布时间】:2017-04-18 05:34:28
【问题描述】:

我正在使用 pdfkit 从字符串生成 pdf 文件。

问: 我传递给 pdfkit 的每个字符串我都希望它作为输出 pdf 中的新页面。

我知道使用下面的 from_file 可以做到这一点。但是,我不想将它写入文件并使用它。

pdfkit.from_file(['file1', 'file2'], 'output.pdf') 这将创建 2 页的 output.pdf 文件。

类似下面的可能吗?

pdfkit.from_string(['ABC', 'XYZ'], 'output.pdf') 

应该在 output.pdf 文件的第 1 页写“ABC”,在第 2 页写“XYZ”

【问题讨论】:

  • 为什么不输入一个字符串并调用github.com/JazzCore/python-pdfkit/blob/…?似乎图书馆对你想要的东西有一定的支持。如果您需要每页的每个文本,请注入 HTML 而不是原始文本。
  • @justderb 没找到你。
  • @justderb by inject html instead of raw text 你的意思是传递文件名列表吗?

标签: python pdfkit python-pdfkit


【解决方案1】:

我知道这是旧的,但万一其他人发现自己在这里,我想我会分享我所做的。我必须实现 PyPDF2 来执行上面指定的操作。我的类似解决方案是:

from PyPDF2 import PdfFileReader, PdfFileWriter
import io


with open('output.pdf', 'wb') as output_file:
    writer = PdfFileWriter()
    for s in ['ABC', 'XYZ']:
        stream = io.BytesIO()
        stream.write(pdfkit.from_string(s, False))
        # This line assumes the string html (or txt) is only 1 page.
        writer.addPage(PdfFileReader(stream).getPage(0))
    writer.write(output_file)

【讨论】:

    【解决方案2】:

    你可以像这样连接字符串:

    pdfkit.from_string('ABC' + 'XYZ', 'output.pdf')
    

    【讨论】:

    • 但这与将内容作为单个字符串传递是一样的。它不会在新页面上开始“XYZ”。
    猜你喜欢
    • 1970-01-01
    • 2015-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-22
    • 1970-01-01
    • 1970-01-01
    • 2014-05-05
    相关资源
    最近更新 更多