实用工具类:java实现图片转PDF格式

最近有个朋友问我有没有免费的图片转PDF格式的软件,我在网上找了很久,发现几乎全部都要收费的,无奈之下,我只要利用自己的特长,用java代码来实现图片转PDF格式的功能,话不多说,立即上代码:

复制代码
/**
	 *
	 * @param imgFilePath img文件路径
	 * @param filePath    文件路径
	 * @throws IOException ioexception
	 */
	private static void downloadPdf(String imgFilePath, String filePath) {
		try {
			// 1.将本地的图片转成流形式
			File imgFile = new File(imgFilePath);
			byte[] imageBytes = readBytesFromFile(imgFile);

			// 2. 生成一页 PDF document
			PDDocument document = new PDDocument();
			PDImageXObject image = PDImageXObject.createFromByteArray(document, imageBytes, "image");
			// 这里是你生成PDF自适应图片大小,不设置会默认为A4
			PDRectangle pageSize = new PDRectangle(image.getWidth(), image.getHeight());
			PDPage page = new PDPage(pageSize);
			document.addPage(page);
			// 3.将 图片 添加进PDF document
			PDPageContentStream contentStream = new PDPageContentStream(document, page);
			float pageWidth = pageSize.getWidth();
			float pageHeight = pageSize.getHeight();
			float imageWidth = image.getWidth();
			float imageHeight = image.getHeight();
			float scale = Math.min(pageWidth / imageWidth, pageHeight / imageHeight);
			float scaledWidth = imageWidth * scale;
			float scaledHeight = imageHeight * scale;
			float x = (pageWidth - scaledWidth) / 2;
			float y = (pageHeight - scaledHeight) / 2;
			// 这里是将你的图片填充入pdf页
			contentStream.drawImage(image, x, y, scaledWidth, scaledHeight);
			contentStream.close();

			// 4. 保存PDF
			File outputFile = new File(filePath);
			File parentFolder = outputFile.getParentFile();
			if (parentFolder != null && !parentFolder.exists()) {
				parentFolder.mkdirs();
			}
			document.save(outputFile);
			document.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 从文件读取字节
	 *
	 * @param file 文件
	 * @return {@link byte[]}
	 * @throws IOException ioexception
	 */
	private static byte[] readBytesFromFile(File file) throws IOException {
		FileInputStream inputStream = new FileInputStream(file);
		byte[] bytes = IOUtils.toByteArray(inputStream);
		inputStream.close();
		return bytes;
	}

注:代码中只需要用到一个jar包,导入jar包后直接在eclipse或者其他java开发工具上运行即可,jar包下载地址:https://dlcdn.apache.org/pdfbox/3.0.2/pdfbox-app-3.0.2.jar

相关推荐
悲喜自渡7211 天前
Docker指令自存
java·docker·eureka
wenxiaohai1231 天前
在anaconda中安装cuda-pytorch
人工智能·pytorch·python·anaconda
Dingdangr1 天前
基于Python的火焰识别系统设计与实现(含论文、开题报告及答辩PPT)
java·python·测试工具·安全
梁同学与Android1 天前
Android ---【经验篇】Fragment 生命周期高频面试题(附标准答案)
java·面试·fragment面试
吴佳浩 Alben1 天前
Python入门指南(五) - 为什么选择 FastAPI?
开发语言·python·fastapi
速易达网络1 天前
Java Web + Vue 前后端分离跨域解决方案
java·开发语言
艺杯羹1 天前
Thymeleaf模板引擎:让Spring Boot页面开发更简单高效
java·spring boot·后端·thymeleadf
山土成旧客1 天前
【Python学习打卡-Day25】从程序崩溃到优雅处理:掌握Python的异常处理艺术
人工智能·python·学习
给你一页白纸1 天前
Pytest 测试用例自动生成:接口自动化进阶实践
python·pytest·接口自动化
小鸡吃米…1 天前
Python - 发送电子邮件
开发语言·python