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

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java可以使用多种库或工具来实现将HTML换为PDF,以下是其中一些常用的方法: 1. 使用iText库 iText是一个流行的Java PDF库,可以使用它来生成PDF文档。可以使用iText将HTML换为PDF,以下是一个简单的示例: ```java import com.itextpdf.text.Document; import com.itextpdf.text.pdf.PdfWriter; import com.itextpdf.tool.xml.XMLWorkerHelper; import java.io.FileOutputStream; import java.io.StringReader; public class HtmlToPdf { public static void main(String[] args) throws Exception { // HTML内容 String html = "<html><body><h1>Hello World!</h1></body></html>"; // 创建PDF文档 Document document = new Document(); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("output.pdf")); document.open(); // 将HTML换为PDF XMLWorkerHelper.getInstance().parseXHtml(writer, document, new StringReader(html)); // 关闭文档 document.close(); } } ``` 2. 使用Flying Saucer库 Flying Saucer是一个基于iText的Java库,可以将HTML和CSS换为PDF。以下是一个简单的示例: ```java import org.xhtmlrenderer.pdf.ITextRenderer; import java.io.FileOutputStream; public class HtmlToPdf { public static void main(String[] args) throws Exception { // HTML内容 String html = "<html><body><h1>Hello World!</h1></body></html>"; // 创建PDF文档 FileOutputStream out = new FileOutputStream("output.pdf"); ITextRenderer renderer = new ITextRenderer(); renderer.setDocumentFromString(html); renderer.layout(); renderer.createPDF(out); // 关闭输出流 out.close(); } } ``` 3. 使用wkhtmltopdf工具 wkhtmltopdf是一个开源的命令行工具,可以将HTML和CSS换为PDF。可以使用Java的Runtime类或ProcessBuilder类来执行wkhtmltopdf命令。以下是一个简单的示例: ```java import java.io.File; public class HtmlToPdf { public static void main(String[] args) throws Exception { // HTML文件路径 String htmlFile = "input.html"; // PDF文件路径 String pdfFile = "output.pdf"; // 执行wkhtmltopdf命令 String[] cmd = {"wkhtmltopdf", htmlFile, pdfFile}; ProcessBuilder pb = new ProcessBuilder(cmd); pb.directory(new File(".")); Process p = pb.start(); int exitCode = p.waitFor(); // 检查命令是否执行成功 if (exitCode == 0) { System.out.println("PDF文件已生成"); } else { System.err.println("换过程出现错误"); } } } ``` 以上是几种常见的Java实现HTMLPDF的方法,具体选择哪一种取决于你的需求和偏好。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值