繁体   English   中英

使用具有自定义尺寸页面和最佳图像分辨率的Reportlab生成PDF

[英]Generate PDF using Reportlab with custom size page and best image resolution

我有一个生成的图像(带有PIL),我必须创建一个具有特定尺寸的PDF,它将包含此(完整尺寸)图像。

我从size= 150mm x 105mm开始,生成了相应的图像1818px x 1287px (带有小边框)(mm至px,具有300dpi ),我使用此代码

pp = 25.4  # 1 pp = 25,4mm
return int((dpi * mm_value) / pp)

现在,我必须创建大小为page = 150mm x 105mm的PDF文件,我使用reportlab并且我将使用具有最佳图像质量的pdf(以进行打印)。

可以指定这个吗?

使用以下命令创建PDF页面大小是正确的:

W = ? // inch value??
H = ? // inch value??
buffer = BytesIO()
p = canvas.Canvas(buffer)
p.setPageSize(size=(W, H)) 

并绘制图像:

p.drawImage(img, 0, 0, width=img.width, preserveAspectRatio=True, mask='auto', anchor='c')

诀窍是在将图像绘制到它之前缩放reportlab的Canvas。 似乎无法从文件中正确提取DPI信息。

此示例代码对我的Laserprinter来说效果很好:

from PIL import Image, ImageDraw, ImageFont
import reportlab.pdfgen.canvas
from reportlab.lib.units import mm

# Create an image with 300DPI, 150mm by 105mm.
dpi = 300
mmwidth = 150
mmheight = 105
pixwidth = int(mmwidth / 25.4 * dpi)
pixheight = int(mmheight / 25.4 * dpi)
im = Image.new("RGB", (pixwidth, pixheight), "white")
dr = ImageDraw.Draw(im)
dr.rectangle((0, 0, pixwidth-1, pixheight-1), outline="black")
dr.line((0, 0, pixwidth, pixheight), "black")
dr.line((0, pixheight, pixwidth, 0), "black")
dr.text((100, 100), "I should be 150mm x 105mm when printed, \
    with a thin black outline, at 300DPI", fill="black")
# A test patch of 300 by 300 individual pixels, 
# should be 1 inch by 1 inch when printed,
# to verify that the resolution is indeed 300DPI.
for y in range(400, 400+300):
    for x in range(500, 500+300):
        if x & 1 and y & 1:
            dr.point((x, y), "black")
im.save("safaripdf.png", dpi=(dpi, dpi))

# Create a PDF with a page that just fits the image we've created.
pagesize = (150*mm, 105*mm)
c = reportlab.pdfgen.canvas.Canvas("safaripdf.pdf", pagesize=pagesize) 
c.scale(0.24, 0.24) # Scale so that the image exactly fits the canvas.
c.drawImage("safaripdf.png", 0, 0) # , width=pixwidth, height=pixheight)

c.showPage()
c.save()

您可能需要稍微调整比例值,以便尺寸完全适合您的打印机,但是上面的值非常接近。 我已经用尺子检查过;-)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM