在开发中根据图片尺寸动态设置PDF文档的宽度和高度是一个常见的需求,以下是完整的解决方案:
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import portrait
from PIL import Image
def create_pdf_from_image(image_path, output_pdf):
# 获取图片尺寸
img = Image.open(image_path)
width, height = img.size
# 转换像素到点(假设72DPI)
pdf_width = width
pdf_height = height
# 创建PDF(尺寸与图片相同)
c = canvas.Canvas(output_pdf, pagesize=portrait((pdf_width, pdf_height)))
# 绘制图片(从左上角开始,占满整个页面)
c.drawImage(image_path, 0, 0, width=pdf_width, height=pdf_height)
c.save()
# 使用示例
create_pdf_from_image("input.jpg", "output.pdf")
const { PDFDocument } = require('pdf-lib');
const fs = require('fs');
const { createCanvas, loadImage } = require('canvas');
async function createPdfFromImage(imagePath, outputPdf) {
const image = await loadImage(imagePath);
const pdfDoc = await PDFDocument.create();
// 使用图片尺寸作为PDF页面尺寸
const page = pdfDoc.addPage([image.width, image.height]);
// 嵌入图片
const imageBytes = fs.readFileSync(imagePath);
const pdfImage = await pdfDoc.embedJpg(imageBytes);
// 绘制图片
page.drawImage(pdfImage, {
x: 0,
y: 0,
width: image.width,
height: image.height,
});
// 保存PDF
const pdfBytes = await pdfDoc.save();
fs.writeFileSync(outputPdf, pdfBytes);
}
// 使用示例
createPdfFromImage('input.jpg', 'output.pdf');
pt = px * (72 / image_dpi)
portrait()
或landscape()
函数处理方向pagesize=(min(width,height), max(width,height))
preserveAspectRatio
以上方案适用于大多数编程场景,可根据具体需求调整参数实现精确控制。