我使用wkhtmltopdf
将(Django模板化的(HTML文档呈现为单页PDF文件。我想立即用正确的高度渲染它(到目前为止我还没有做到(,或者不正确地渲染并修剪它。我使用的是Python。
尝试类型1:
wkhtmltopdf
使用--page-height
渲染为非常非常长的单页PDF,具有大量额外空间- 使用
pdfCropMargins
修剪:crop(["-p4", "100", "0", "100", "100", "-a4", "0", "-28", "0", "0", "input.pdf"])
PDF的底部有28个单位的空白,但我不得不使用文件系统来执行crop
命令。该工具似乎期望有一个输入文件和一个输出文件,并在中途创建临时文件。所以我不能用它。
尝试类型2:
wkhtmltopdf
使用默认参数渲染为多页PDF- 使用
PyPDF4
(或PyPDF2
(读取文件并将页面组合为一个长的单页
在大多数情况下,PDF的渲染都很好,但是,如果碰巧上一个PDF页面的内容很少,有时会在底部看到很多额外的空白。
理想场景:
理想的场景是使用一个函数,该函数接受HTML并将其呈现为单页PDF,底部有预期的空白量。我很乐意使用wkhtmltopdf
渲染PDF,因为它返回字节,然后处理这些字节以去除任何多余的空白。但我不想让文件系统参与其中,相反,我想在内存中执行所有操作。也许我可以以某种方式直接检查PDF并手动删除空白,或者做一些HTML魔术来提前确定渲染高度?
我现在在做什么:
注意pdfkit
是wkhtmltopdf
包装器
# This is not a valid HTML (includes Django-specific stuff)
template: Template = get_template("some-django-template.html")
# This is now valid HTML
rendered = template.render({
"foo": "bar",
})
# This first renders PDF from HTML normally (multiple pages)
# Then counts how many pages were created and determines the required single-page height
# Then renders a single-page PDF from HTML using the page height and width arguments
return pdfkit.from_string(rendered, options={
"page-height": f"{297 * PdfFileReader(BytesIO(pdfkit.from_string(rendered))).getNumPages()}mm",
"page-width": "210mm"
})
它相当于Attempt type 2
,只是我在这里不使用PyDPF4
将页面缝合在一起,而是使用预先计算的页面高度用wkhtmltopdf
再次渲染。
也许有更好的方法可以做到这一点,但这至少有效。
我假设你可以自己裁剪PDF,我在这里所做的就是确定你在最后一页上还有多少内容。如果这个假设是错误的,我可能会想出如何裁剪PDF。或者,只需裁剪图像(在Pillow中很容易(,然后将其转换为PDF?
此外,如果你有一个大的PDF,你可能需要弄清楚整个PDF的末尾有多远。我只是想知道最后一页的内容结束了多远。但从一个转换到另一个就像一个简单的算术问题。
测试代码:
import pdfkit
from PyPDF2 import PdfFileReader
from io import BytesIO
# This library isn't named fitz on pypi,
# obtain this library with `pip install PyMuPDF==1.19.4`
import fitz
# `pip install Pillow==8.3.1`
from PIL import Image
import numpy as np
# However you arrive at valid HTML, it makes no difference to the solution.
rendered = "<html><head></head><body><h3>Hello World</h3><p>hello</p></body></html>"
# This first renders PDF from HTML normally (multiple pages)
# Then counts how many pages were created and determines the required single-page height
# Then renders a single-page PDF from HTML using the page height and width arguments
pdf_bytes = pdfkit.from_string(rendered, options={
"page-height": f"{297 * PdfFileReader(BytesIO(pdfkit.from_string(rendered))).getNumPages()}mm",
"page-width": "210mm"
})
# convert the pdf into an image.
pdf = fitz.open(stream=pdf_bytes, filetype="pdf")
last_page = pdf[pdf.pageCount-1]
matrix = fitz.Matrix(1, 1)
image_pixels = last_page.get_pixmap(matrix=matrix, colorspace="GRAY")
image = Image.frombytes("L", [image_pixels.width, image_pixels.height], image_pixels.samples)
#Uncomment if you want to see.
#image.show()
# Now figure out where the end of the text is:
# First binarize. This might not be the most efficient way to do this.
# But it's how I do it.
THRESHOLD = 100
# I wrote this code ages ago and don't remember the details but
# basically, we treat every pixel > 100 as a white pixel,
# We convert the result to a true/false matrix
# And then invert that.
# The upshot is that, at the end, a value of "True"
# in the matrix will represent a black pixel in that location.
binary_matrix = np.logical_not(image.point( lambda p: 255 if p > THRESHOLD else 0 ).convert("1"))
# Now find last white row, starting at the bottom
row_count, column_count = binary_matrix.shape
last_row = 0
for i, row in enumerate(reversed(binary_matrix)):
if any(row):
last_row = i
break
else:
continue
percentage_from_top = (1 - last_row / row_count) * 100
print(percentage_from_top)
# Now you know where the page ends.
# Go back and crop the PDF accordingly.