- package com.cinc.messageservice.message.mail.util;
- import com.cinc.messageservice.utils.EmptyUtils;
- import com.itextpdf.html2pdf.ConverterProperties;
- import com.itextpdf.html2pdf.HtmlConverter;
- import com.itextpdf.kernel.geom.PageSize;
- import com.itextpdf.kernel.PDF.PdfDocument;
- import com.itextpdf.kernel.PDF.PdfWriter;
- import com.itextpdf.styledxmlparser.CSS.media.MediaDeviceDescription;
- import com.itextpdf.styledxmlparser.CSS.media.MediaType;
- import com.itextpdf.text.*;
- import com.itextpdf.text.PDF.*;
- import com.itextpdf.tool.xml.XMLWorkerFontProvider;
- import java.io.*;
- import java.NET.URL;
- import java.util.HashMap;
- import java.util.Map;
- /**
- * @Author: hhr
- * @Despriction:
- * @CreatedTime: 2020/3/12 16:39
- * @ModifyBy:
- * @ModifyTime:
- * @ModifyDespriction:
- * @Version: V1.0.0
- */
- public class PdfUtil {
- // 默认中文字体
- private static final String FONT = "C:\\Windows\\Fonts\\simhei.ttf";
- /**
- * 根据模板将数据输出 PDF 文件
- * @param tagetPath
- * @param templatePath
- * @param dataMap
- * @param imageMap
- * @throws Exception
- */
- public static void templeteToPdf(String tagetPath, String templatePath, Map<String, Object> dataMap, Map<String, Object> imageMap) throws Exception {
- PdfReader reader;
- FileOutputStream out;
- ByteArrayOutputStream bos;
- PdfStamper stamper;
- try {
- BaseFont bf = BaseFont.createFont(FONT , BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
- Font fontChinese = new Font(bf, 5, Font.NORMAL);
- out = new FileOutputStream(tagetPath);// 输出流
- reader = new PdfReader(templatePath);// 读取 PDF 模板
- bos = new ByteArrayOutputStream();
- stamper = new PdfStamper(reader, bos);
- AcroFields form = stamper.getAcroFields();
- // 文字类的内容处理
- form.addSubstitutionFont(bf);
- if (!EmptyUtils.isMapEmpty(dataMap)){
- for(String key : dataMap.keySet()){
- String value = (String)dataMap.get(key);
- form.setField(key,value);
- }
- }
- // 图片类的内容处理
- if (!EmptyUtils.isMapEmpty(imageMap)){
- for(String key : imageMap.keySet()) {
- String value = (String)imageMap.get(key);
- String imgpath = value;
- int pageNo = form.getFieldPositions(key).get(0).page;
- Rectangle signRect = form.getFieldPositions(key).get(0).position;
- float x = signRect.getLeft();
- float y = signRect.getBottom();
- // 根据路径读取图片
- Image image = Image.getInstance(imgpath);
- // 获取图片页面
- PdfContentByte under = stamper.getOverContent(pageNo);
- // 图片大小自适应
- image.scaleToFit(signRect.getWidth(), signRect.getHeight());
- // 添加图片
- image.setAbsolutePosition(x, y);
- under.addImage(image);
- }
- }
- // 如果为 false, 生成的 PDF 文件可以编辑, 如果为 true, 生成的 PDF 文件不可以编辑
- stamper.setFormFlattening(true);
- stamper.close();
- Document doc = new Document();
- Font font = new Font(bf, 32);
- PdfCopy copy = new PdfCopy(doc, out);
- doc.open();
- PdfImportedPage importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), 1);
- copy.addPage(importPage);
- doc.close();
- } catch (IOException e) {
- System.out.println(e);
- } catch (DocumentException e) {
- System.out.println(e);
- }
- }
- /**
- * HTML 转 PDF
- * @param sourcePath
- * @param tagetPath
- * @param pageSize
- * @param baseuri
- * @throws Exception
- */
- public static void htmlToPdf(String sourcePath, String tagetPath, PageSize pageSize, String baseuri) throws Exception {
- PdfWriter writer = new PdfWriter(tagetPath);
- PdfDocument pdfDocument = new PdfDocument(writer);
- pdfDocument.setTagged();
- // 设置页面大小
- pdfDocument.setDefaultPageSize(pageSize);
- ConverterProperties converterProperties = new ConverterProperties();
- converterProperties.setBaseUri(baseuri);
- MediaDeviceDescription mediaDeviceDescription = new MediaDeviceDescription(MediaType.SCREEN);
- mediaDeviceDescription.setWidth(pageSize.getWidth());
- converterProperties.setMediaDeviceDescription(mediaDeviceDescription);
- URL url = new URL(sourcePath);
- InputStream inputStream = url.openStream();
- //InputStream inputStream = new FileInputStream(sourcePath);
- HtmlConverter.convertToPdf(inputStream, pdfDocument, converterProperties);
- inputStream.close();
- }
- /**
- * 对图片转 PDF
- * @param picturePath
- * @param os
- */
- public static void imageToPDF(String picturePath, OutputStream os) {
- try {
- Document document = new Document(com.itextpdf.text.PageSize.A4);
- com.itextpdf.text.PDF.PdfWriter.getInstance(document, os);
- document.open();
- // 重新设置宽高
- Image image = Image.getInstance(picturePath);
- float documentWidth = document.getPageSize().getWidth() - document.leftMargin() - document.rightMargin();
- float documentHeight = documentWidth / 580 * 320;
- image.scaleAbsolute(documentWidth, documentHeight);
- document.add(image);
- document.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- /**
- * txt 文件转 PDF 文件
- * @param text
- * @param os
- * @throws DocumentException
- * @throws IOException
- */
- public static void textToPDF(String text, OutputStream os) throws DocumentException, IOException {
- Document document = new Document();
- com.itextpdf.text.PDF.PdfWriter.getInstance(document, os);
- document.open();
- // 方法一: 使用 Windows 系统字体 (TrueType)
- BaseFont baseFont = BaseFont.createFont(FONT, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
- Font font = new Font(baseFont);
- InputStreamReader isr = new InputStreamReader(new FileInputStream(new File(text)), "GBK");
- BufferedReader bufferedReader = new BufferedReader(isr);String str = "";
- while ((str = bufferedReader.readLine()) != null) {
- document.add(new Paragraph(str,font));
- }
- document.close();
- }
- public static void main(String[] args) throws Exception{
- /* HashMap<String, Object> dataMap = new HashMap<>();
- HashMap<String,Object> imageMap = new HashMap<>();
- imageMap.put("image", "E:\\aaa\\11.jpg");
- dataMap.put("name", "测试 Test");
- dataMap.put("projectName", "西山采购项目");
- dataMap.put("stock", "前山库房");
- dataMap.put("code", "001");
- dataMap.put("fill_4", "水浒");
- dataMap.put("fill_5", "1");
- dataMap.put("fill_6", "1");
- dataMap.put("fill_7", "1");
- dataMap.put("fill_8", "2");
- dataMap.put("fill_9", "11");
- dataMap.put("fill_10", "12");
- templeteToPdf("E:\\aaa\\tp.pdf","E:\\aaa\\toPDF.pdf",dataMap, imageMap);
- String image = "E:\\aaa\\aa.txt";
- OutputStream os = new FileOutputStream("E:\\aaa\\b.pdf");*/
- htmlToPdf("https://wenku.baidu.com/view/6f1509a5d0f34693daef5ef7ba0d4a7303766c5b.html?rec_flag=default", "E:\\aaa\\p.pdf", PageSize.A2, "https://blog.csdn.net/erlian1992/article/details/82631290");
- }
- }
- /**
- * 用于中文显示的 Provider
- */
- class AsianFontProvider extends XMLWorkerFontProvider {
- @Override
- public Font getFont(final String fontname, String encoding, float size, final int style) {
- try {
- BaseFont bfChinese = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
- return new Font(bfChinese, size, style);
- } catch (Exception e) {
- }
- return super.getFont(fontname, encoding, size, style);
- }
- }
- dependency>
- <groupId>com.itextpdf</groupId>
- <artifactId>itextpdf</artifactId>
- <version>5.5.11</version>
- </dependency>
- <dependency>
- <groupId>com.itextpdf.tool</groupId>
- <artifactId>xmlworker</artifactId>
- <version>5.5.11</version>
- </dependency>
- <dependency>
- <groupId>com.itextpdf</groupId>
- <artifactId>itext-asian</artifactId>
- <version>5.2.0</version>
- </dependency>
- <dependency>
- <groupId>com.itextpdf</groupId>
- <artifactId>html2pdf</artifactId>
- <version>2.1.5</version>
- </dependency>
模板生成 PDF 文件时, 需要用 Adobe Acrobat DC 工具编辑模板
来源: http://www.bubuko.com/infodetail-3483831.html