java使用itextpdf根据html模板生成pdf,将多页pdf合并成一页,将多页pdf合并成一张图片,整体缩放pdf内容

pom文件

   <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.5.13</version>
        </dependency>
        
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>html2pdf</artifactId>
            <version>4.0.3</version>
        </dependency>
        
        <dependency>
            <groupId>org.apache.pdfbox</groupId>
            <artifactId>pdfbox</artifactId>
            <version>2.0.21</version>
        </dependency>

        <dependency>
            <groupId>org.apache.pdfbox</groupId>
            <artifactId>pdfbox-tools</artifactId>
            <version>2.0.9</version>
        </dependency>

效果展示:

原pdf为两页:
在这里插入图片描述
转成PNG图片:
在这里插入图片描述
转成两页合并后的pdf:
在这里插入图片描述
整体缩放后: 完美合并
![在这里插入图片描述](https://img-blog.csdnimg.cn/direct/47207878bae7463ca8e309fad0ea05d1.png在这里插入图片描述


代码:

//content为html模板填充后的html字符串数据  outpath为目标文件输出地址全路径
public static boolean html2Pdf(String content, String outPath) {
        try {
            ConverterProperties converterProperties = new ConverterProperties();
            converterProperties.setCharset("UTF-8");
            FontProvider fontProvider = new FontProvider();
            fontProvider.addSystemFonts();
            converterProperties.setFontProvider(fontProvider);
            //关键合并
            PdfDocument temp = new PdfDocument(new PdfWriter(new FileOutputStream(outPath)));
            //根据数据最多的情况 调整合适大小
            temp.setDefaultPageSize(PageSize.A0);
            HtmlConverter.convertToPdf(content, temp, converterProperties);
            File file = new File(outPath);
            String ta = outPath.substring(0, outPath.lastIndexOf('.')) + "new.pdf";
            int a = 20;
            //转图片
            //Pdf2Png.pdfFileToImage(file,ta,a);
            //2页合并一页
            //Pdf2Png.mergeTwoPagesIntoOne(outPath,ta);
            //整体缩放pdf
                String shrunkenPath = ta;
                PdfWriter pdfWriter = new PdfWriter(shrunkenPath);
                PdfDocument shrunkenDocument = new PdfDocument(pdfWriter);
                String originalPath = outPath;
                PdfReader pdfReader = new PdfReader(originalPath);
                PdfDocument originalDocument= new PdfDocument(pdfReader);
                PdfPage orignalPage= originalDocument.getPage(1);
                Rectangle originalPDFSizes = orignalPage.getPageSize();
                PdfPage emptyPage = shrunkenDocument.addNewPage();
                Rectangle emptyPDFsizes= emptyPage.getPageSize();
                double width = emptyPDFsizes.getWidth()/ originalPDFSizes.getWidth();
                double height = emptyPDFsizes.getHeight() / originalPDFSizes.getHeight();
                double newWidth = width / 2;
                double newHeight = height / 2;
                AffineTransform affineTransform = AffineTransform.getScaleInstance( newWidth, newHeight);
                PdfCanvas canvas = new PdfCanvas(emptyPage);
                canvas.concatMatrix(affineTransform);
                PdfFormXObject pageCopy= orignalPage.copyAsFormXObject( shrunkenDocument);
                canvas.addXObject(pageCopy, (float)newWidth, (float)newHeight);
                Document doc = new Document(shrunkenDocument);
                doc.close();
                originalDocument.close();
        } catch (Exception e) {
            log.error("生成模板内容失败,{}",e);
            return false;
        }
        return true;
    }

工具类:

package com.haihu.common.utils.pdf;


import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.RectangleReadOnly;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfWriter;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 小于转暴雨??
 * @date 2023/3/1 14:53
 */
public class Pdf2Png {

    public static void main(String[] args) {
        File file = new File("E:\git\hosp_front\public\view\20230216\张金妹.pdf");
        String ta = "E:\git\hosp_front\public\view\20230216\张金妹.png";
        int a = 20;
        pdfFileToImage(file,ta,a);
    }
    public static void mergeTwoPagesIntoOne(String originalPdfFile, String outputPdfFile) throws IOException, DocumentException {
        PdfReader reader = new PdfReader(originalPdfFile);
        Document doc = new Document(new RectangleReadOnly(842f, 595f), 0, 0, 0, 0);
        PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(outputPdfFile));
        doc.open();
        int totalPages = reader.getNumberOfPages();
        for (int i = 1; i <= totalPages; i = i + 2) {
            doc.newPage();
            PdfContentByte cb = writer.getDirectContent();
            PdfImportedPage page = writer.getImportedPage(reader, i); // page #1

            float documentWidth = doc.getPageSize().getWidth() / 2;
            float documentHeight = doc.getPageSize().getHeight();
            if (i > 1)
                documentHeight = documentHeight - 50f;

            float pageWidth = page.getWidth();
            float pageHeight = page.getHeight();

            float widthScale = documentWidth / pageWidth;
            float heightScale = documentHeight / pageHeight;
            float scale = Math.min(widthScale, heightScale);

            float offsetX = (documentWidth - (pageWidth * scale)) / 2;
            float offsetY = 0f;

            cb.addTemplate(page, scale, 0, 0, scale, offsetX, offsetY);

            if (i+1 <= totalPages) {
                PdfImportedPage page2 = writer.getImportedPage(reader, i+1); // page #2

                pageWidth = page.getWidth();
                pageHeight = page.getHeight();

                widthScale = documentWidth / pageWidth;
                heightScale = documentHeight / pageHeight;
                scale = Math.min(widthScale, heightScale);

                offsetX = ((documentWidth - (pageWidth * scale)) / 2) + documentWidth;
                cb.addTemplate(page2, scale, 0, 0, scale, offsetX, offsetY);
            }
        }
        doc.close();
    }
    /**
     * pdf文件图像
     * 这里的路径一定要具体到文件本身,不能直到文件夹,
     * 如果只到文件夹会出现拒绝访问的错误,具体可以看上面main方法
     *
     * @param pdffile       pdf路径
     * @param targetPath    图片路径
     * @param height_offset 高度
     */
    public static void pdfFileToImage(File pdffile, String targetPath,int height_offset) {
        try {
            FileInputStream instream = new FileInputStream(pdffile);
            InputStream byteInputStream = null;
            try {
                PDDocument doc = PDDocument.load(instream);
                PDFRenderer renderer = new PDFRenderer(doc);
                int pageCount = doc.getNumberOfPages();
                List<BufferedImage> list = new ArrayList<BufferedImage>();
                if (pageCount > 0) {

                    int totalHeight = 0;
                    int width = 0;

                    for (int i = 0; i < pageCount; i++) {
                        BufferedImage image = renderer.renderImage(i, 1.25f);
                        list.add(image);
                        totalHeight += image.getHeight();
                        if (width < image.getWidth()) {
                            width = image.getWidth();
                        }
                        image.flush();
                    }

                    BufferedImage tag = new BufferedImage(width, totalHeight, BufferedImage.TYPE_INT_RGB);

                    tag.getGraphics();

                    Graphics g = tag.createGraphics();

                    int startHeight = 0;
                    for (BufferedImage image : list) {
                        g.drawImage(image, 0, startHeight, width, image.getHeight(), null);
                        g.drawImage(image, 0, startHeight, width, image.getHeight(), null);
                        startHeight += image.getHeight() + height_offset;
                    }
                    g.dispose();

                    ByteArrayOutputStream bs = new ByteArrayOutputStream();
                    ImageOutputStream imOut;
                    imOut = ImageIO.createImageOutputStream(bs);
                    ImageIO.write(tag, "png", imOut);
                    byteInputStream = new ByteArrayInputStream(bs.toByteArray());
                    byteInputStream.close();

                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            File uploadFile = new File(targetPath);
            FileOutputStream fops;
            fops = new FileOutputStream(uploadFile);
            fops.write(readInputStream(byteInputStream));
            fops.flush();
            fops.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static byte[] readInputStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        inStream.close();
        return outStream.toByteArray();
    }



}