实用工具类: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

相关推荐
写bug写bug9 分钟前
手把手教你使用JConsole
java·后端·程序员
异常君10 分钟前
Java 中 try-catch 的性能真相:全面分析与最佳实践
java·面试·代码规范
深科文库28 分钟前
构建 MCP 服务器:第 4 部分 — 创建工具
python·chatgpt·prompt·aigc·agi·ai-native
witton33 分钟前
美化显示LLDB调试的数据结构
数据结构·python·lldb·美化·debugger·mupdf·pretty printer
程序员清风1 小时前
阿里二面:Kafka 消费者消费消息慢(10 多分钟),会对 Kafka 有什么影响?
java·后端·面试
幼稚园的山代王1 小时前
Prompt Enginering(提示工程)先进技术
java·人工智能·ai·chatgpt·langchain·prompt
周某某~1 小时前
二.单例模式‌
java·单例模式·设计模式
摸鱼仙人~1 小时前
深入理解Java单例模式:确保类只有一个实例
java·javascript·单例模式
nenchoumi31191 小时前
AirSim/Cosys-AirSim 游戏开发(一)XBox 手柄 Windows + python 连接与读取
windows·python·xbox
GoodStudyAndDayDayUp1 小时前
初入 python Django 框架总结
数据库·python·django