Java itextpdf工具包 HTML转PDF(支持中文)

0.设置本地字体文件

字体获得:‪Windows系统:C:\Windows\Fonts\,拷贝过去就行
在这里插入图片描述

1.源码

pom坐标

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

工具类

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.ElementList;
import com.itextpdf.tool.xml.XMLWorker;
import com.itextpdf.tool.xml.XMLWorkerFontProvider;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import com.itextpdf.tool.xml.css.CssFile;
import com.itextpdf.tool.xml.css.StyleAttrCSSResolver;
import com.itextpdf.tool.xml.html.CssAppliers;
import com.itextpdf.tool.xml.html.CssAppliersImpl;
import com.itextpdf.tool.xml.html.Tags;
import com.itextpdf.tool.xml.parser.XMLParser;
import com.itextpdf.tool.xml.pipeline.css.CSSResolver;
import com.itextpdf.tool.xml.pipeline.css.CssResolverPipeline;
import com.itextpdf.tool.xml.pipeline.end.ElementHandlerPipeline;
import com.itextpdf.tool.xml.pipeline.html.HtmlPipeline;
import com.itextpdf.tool.xml.pipeline.html.HtmlPipelineContext;

/**
 * @description html转pdf 支持中文内容
 * @date 2023/11/9
 */

public class HtmlToPdfUtils {

	private static final Logger log = Logger.getLogger(HtmlToPdfUtils.class.getName());

	private HtmlToPdfUtils() {
	}

	/**
	 * 创建包含单词的PDF
	 *
	 * @param htmlStr 字符串
	 * @param pdfPath pdf路径
	 * @throws IOException
	 * @throws DocumentException
	 */
	public static void creatHtmlpdf(String htmlStr, String pdfPath) throws IOException, DocumentException {
		// step 1 new Document 默认大小A4
		Document document = new Document(PageSize.A4.rotate());
		// step 2
		PdfWriter.getInstance(document, Files.newOutputStream(Paths.get(pdfPath)));
		// step 3
		document.open();
		// step 4
		Paragraph context = new Paragraph();
		ElementList elementList = parseToElementList(htmlStr, null);
		context.addAll(elementList);
		document.add(context);
		// step 5
		document.close();
	}

	/**
	 * 设置字体信息
	 *
	 * @return
	 */
	private static Font getFontInf() {
		// 字体路径
		String fontPath = "src/main/webapp/font/simhei.ttf";
		BaseFont baseFont = null;
		Font font = null;
		try {
			// 设置字体路径,字体编码,是否将字体嵌入pdf(默认false)
			baseFont = BaseFont.createFont(fontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
			// 设置默认字体数据
			font = new Font(baseFont, 12f, Font.NORMAL, BaseColor.BLACK);
		} catch (DocumentException | IOException e) {
			log.log(Level.SEVERE, "获取pdf字体信息失败", e);
		}
		return font;
	}

	/**
	 * html转pdf 写法
	 *
	 * @param html
	 * @param css
	 * @return
	 * @throws IOException
	 */
	public static ElementList parseToElementList(String html, String css) throws IOException {
		// CSS
		CSSResolver cssResolver = new StyleAttrCSSResolver();
		if (css != null) {
			CssFile cssFile = XMLWorkerHelper.getCSS(new ByteArrayInputStream(css.getBytes()));
			cssResolver.addCss(cssFile);
		}

		// HTML
		MyFontsProvider fontProvider = new MyFontsProvider();
		CssAppliers cssAppliers = new CssAppliersImpl(fontProvider);
		HtmlPipelineContext htmlContext = new HtmlPipelineContext(cssAppliers);
		htmlContext.setTagFactory(Tags.getHtmlTagProcessorFactory());
		htmlContext.autoBookmark(false);

		// Pipelines
		ElementList elements = new ElementList();
		ElementHandlerPipeline end = new ElementHandlerPipeline(elements, null);
		HtmlPipeline htmlPipeline = new HtmlPipeline(htmlContext, end);
		CssResolverPipeline cssPipeline = new CssResolverPipeline(cssResolver, htmlPipeline);

		// XML Worker
		XMLWorker worker = new XMLWorker(cssPipeline, true);
		XMLParser p = new XMLParser(worker);
		html = html.replace("<br>", "").replace("<hr>", "").replace("<img>", "").replace("<param>", "").replace("<link>", "");
		p.parse(new ByteArrayInputStream(html.getBytes()));
		return elements;
	}

	static class MyFontsProvider extends XMLWorkerFontProvider {
		public MyFontsProvider() {
			super(null, null);
		}

		@Override
		public Font getFont(final String fontname, String encoding, float size, final int style) {
			return getFontInf();
		}
	}


	public static void main(String[] args) throws DocumentException, IOException {
		String htmlPath = "D:\\工作文件夹\\index.html"; // 输入HTML文件的路径
		String pdfPath = "D:\\工作文件夹\\index.pdf"; // 输出PDF文件的路径
		// 获取html内容文字
		String htmlContent = new String(Files.readAllBytes(Paths.get(htmlPath)));
		creatHtmlpdf(htmlContent, pdfPath);
	}
}


2.HTML范例:

<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
    body {
        width: 35em;
        margin: 0 auto;
        font-family: Tahoma, Verdana, Arial, sans-serif;
    }
</style>
</head>
<body>
<h1>Welcome to nginx!啊啊啊啊啊啊啊啊啊啊啊啊</h1>
<h1>Welcome to nginx!字體文件不存在,影響倒出pdf中文顯示</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>

<p><em>Thank you for using nginx.</em></p>
</body>
</html>

在这里插入图片描述
转出结果:
在这里插入图片描述

1、解决中文问题 2、附字体 3、动态html拼接pdf public static void htmlCodeComeString(String linkcss,String htmlCode, String outputFile,String title) throws Exception { OutputStream os = new FileOutputStream(outputFile); ITextRenderer renderer = new ITextRenderer(); renderer.setDocumentFromString(getConversionHtmlCode(linkcss,htmlCode,title)); ITextFontResolver fontResolver = renderer.getFontResolver(); URL fontPath = ItextUtil.class.getResource("simsun.ttc"); fontResolver.addFont(fontPath.toString(), BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); // 解决图片的相对路径问题 // renderer.getSharedContext().setBaseURL("file:/F:/teste/html/"); renderer.layout(); renderer.createPDF(os); System.out.println("======换成功!"); os.close(); os.flush(); } public static void main(String[] args) { ItextUtil itextUtil = new ItextUtil(); String html = ""; html += ""; html += "企业信息"; html += " "; html += " "; html += " 登记日期"; html += " 2006-04-28"; html += " "; html += " "; html += " 纳税人编号"; html += " HSJIHKS002"; html += " "; html += " "; html += " 有效标志"; html += " Y"; html += " "; html += " "; html += " 社会信用代码"; html += " 916101317H"; html += " "; html += " "; html += " 评估机关代码"; html += " 盛世"; html += " "; html += " "; html += " 工商注销日期"; html += " 2006-04-28"; html += " "; html += " "; html += ""; String outputFile = "D:\\pdf\\aa.pdf"; try { itextUtil.htmlCodeComeString("",html,outputFile,""); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("生成结束!!!"); }
iTextPDF是一个强大的Java库,用于创建、读取和修改PDF文档。如果你想要将PDF换成图像文件(如PNG或JPEG),你可以利用iTextPDF的一些关键功能。 ### 使用步骤: #### 步骤 1 - 导入依赖 首先,你需要在项目中导入iText的相关依赖。如果使用Maven,可以在`pom.xml`文件中添加以下依赖: ```xml <dependencies> <dependency> <groupId>com.itextpdf</groupId> <artifactId>itextpdf</artifactId> <version>7.1.4</version> <!-- 或者你使用的其他版本 --> </dependency> </dependencies> ``` #### 步骤 2 - 加载 PDF 文档 接下来,你需要加载你想换为图像的PDF文件。可以使用 `PdfReader` 类来完成这一操作。 ```java import com.itextpdf.kernel.pdf.PdfDocument; import com.itextpdf.kernel.pdf.PdfReader; try { PdfReader reader = new PdfReader("path_to_your_pdf_file.pdf"); } catch (Exception e) { // Handle exception } ``` #### 步骤 3 - 获取页面并创建 Image 对象 遍历PDF文档的每一页,并从每页中提取数据。之后,可以使用 `Image` 类将每一帧换为图像文件。 ```java import com.itextpdf.kernel.image.Image; import com.itextpdf.layout.Document; import javax.imageio.ImageIO; for(int i=1; i<=reader.getNumberOfPages(); i++) { Document doc = new Document(reader.getPage(i)); try { Image img = Image.getInstance(doc); String imagePath = "path_to_output_image_" + i + ".jpg"; // 自定义输出路径 ImageIO.write(img.getImage(), "jpg", new File(imagePath)); } catch (Exception e) { // Handle exception } } reader.close(); ``` ### 相关问题: 1. **如何调整图像大小?** 当使用iTextPDFPDF为图像时,默认会按照PDF页面的比例生成图像。若需自定义尺寸,可在创建`Image`实例时传递宽度和高度参数。 2. **能否将PDF的部分内容提取出来作为图片?** 可以通过指定`PdfReader`时传入页码范围或特定页面索引来只处理部分页面内容。 3. **iTextPDF是否支持多种输出格式?** 是的,除了常见的JPG和PNG格式外,iText支持其他格式,如SVG,可通过调整`ImageIO.write()`方法中的第二个参数来选择输出格式。例如:`ImageIO.write(img.getImage(), "svg", new File(imagePath));`。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值