java用图片生成pdf

该代码示例展示了如何在Java中利用Maven引入iTextPDF库,然后将指定的图片转换成PDF文件。通过设置页面大小、调整图片比例并添加到PDF文档中,最终生成PDF文件并保存至特定路径。
摘要由CSDN通过智能技术生成

maven引入组件itextpdf

<dependency>
   <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.13.3</version>
</dependency>

java将图片转pdf

public static File Pdf(String imageUrl, String mOutputPdfFileName) {
	Document doc = new Document(PageSize.A4, 0, 0, 0, 0); //new一个pdf文档
	doc.setMargins(0f, 0f, 12f, 0f);
	try {
		PdfWriter.getInstance(doc, new FileOutputStream(mOutputPdfFileName)); //pdf写入
		doc.open();//打开文档
		doc.newPage();  //在pdf创建一页
		Image png1 = Image.getInstance(imageUrl); //通过文件路径获取image
		float heigth = png1.getHeight();
		float width = png1.getWidth();
		int percent = getPercent2(heigth, width)+2;
		png1.setAlignment(Image.MIDDLE);
		png1.scalePercent(percent);// 表示是原来图像的比例;
		doc.add(png1);
		
		doc.close();
		System.out.println("生成pdf "+mOutputPdfFileName);
	} catch (FileNotFoundException e) {
		e.printStackTrace();
	} catch (DocumentException e) {
		e.printStackTrace();
	} catch (IOException e) {
		e.printStackTrace();
	}
	File mOutputPdfFile = new File(mOutputPdfFileName);  //输出流
	if (!mOutputPdfFile.exists()) {
		mOutputPdfFile.deleteOnExit();
		return null;
	}
	return mOutputPdfFile; //反回文件输出流
}

public static int getPercent2(float h, float w) {
    int p = 0;
    float p2 = 0.0f;
    p2 = 530 / w * 100;
    p = Math.round(p2);
    return p;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yfx000

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值