IText生成PDF删除与合并

2023-01-02 00:00:00 删除 合并 生成

效果图:
《IText生成PDF删除与合并》
添加依赖:

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

        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext-asian</artifactId>
            <version>5.2.0</version>
        </dependency>
import com.itextpdf.text.*;
import com.itextpdf.text.Font;
import com.itextpdf.text.pdf.*;

import java.io.File;
import java.io.FileOutputStream;

public class PDFDemo { 
    public static void main(String[] args) throws Exception { 
        String filePath = "E:\\work\\idea\\project\\pdf\\src\\main\\resources\\" + System.currentTimeMillis() + ".pdf";
        String title = "国务院国庆放假通知";
        String swDate = "2020-8-11";
        String no = "2037";
        String lwjg = "国务院";
        String wh = "";
        String fileTitle = " 关于国庆放假的通知";
        String tldps = "";
        String nbyj = " 经国务院批准,现将2020年国庆节和中秋节放假调休日期的具体安排通知如下"
                + "\n 10月1日至8日放假调休,共8天。9月27日(星期日)、10月10日(星期六)上班。。";
        generatePDF(filePath, title, swDate, no, lwjg, wh, fileTitle, tldps, nbyj);
    }


    public static String generatePDF(String filePath, String title, String swDate, String no, String lwjg, String wh, String fileTitle, String tldps, String nbyj) throws Exception { 
        Document document = new Document();
        PdfWriter.getInstance(document, new FileOutputStream(filePath));
        document.open();
        document.newPage();

        //标题
        BaseFont baseFont = BaseFont.createFont("C:/Windows/Fonts/SIMYOU.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

        Font font = new Font(baseFont, 20, Font.BOLD, new BaseColor(199, 95, 68));
        Phrase phrase = new Phrase(50, title, font);
        Paragraph paragraph = new Paragraph(phrase);
        paragraph.setAlignment(Element.ALIGN_CENTER);
        document.add(paragraph);

        //
        BaseFont bfChinese = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
// bfChinese = BaseFont.createFont("E:\\work\\idea\\project\\pdf\\src\\main\\resources\\方正仿宋_GBK.TTF", BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);
        font = new Font(bfChinese, 14, Font.NORMAL);
        font.setColor(BaseColor.BLACK);

        PdfPTable t1 = new PdfPTable(2);
        // 设置表格宽度比例为%100
        t1.setWidthPercentage(88);
        // 设置表格的宽度
        t1.setTotalWidth(500);
        // 也可以每列分别设置宽度
        t1.setTotalWidth(new float[]{ 220, 220});
        // 锁住宽度
        t1.setLockedWidth(true);
        // 设置表格上面空白宽度
        t1.setSpacingBefore(15f);

        PdfPCell cA = new PdfPCell(new Paragraph("收文时间:" + swDate, font));
        cA.setBorder(0);
        t1.addCell(cA);

        PdfPCell cB = new PdfPCell(new Paragraph("第" + no + "号", font));
        cB.setBorder(0);
        cB.setHorizontalAlignment(Element.ALIGN_RIGHT);
        t1.addCell(cB);

        document.add(t1);


        //表格

        PdfPTable table = new PdfPTable(4);
        // 设置表格宽度比例为%100
        table.setWidthPercentage(100);
        // 设置表格的宽度
        table.setTotalWidth(500);
        // 也可以每列分别设置宽度
        table.setTotalWidth(new float[]{ 45, 200, 40, 200});
        // 锁住宽度
        table.setLockedWidth(true);
        // 设置表格上面空白宽度
        table.setSpacingBefore(10f);

        // 构建每个单元格
        PdfPCell cell11 = new PdfPCell(new Paragraph("来文机关", font));
        cell11.disableBorderSide(10);
        cell11.setLeading(1.1F, 1.1f);
        cell11.setPaddingBottom(8);
        cell11.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell11.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(cell11);

        PdfPCell cell12 = new PdfPCell(new Paragraph(lwjg, font));
        cell12.disableBorderSide(10);
        cell12.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell12.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(cell12);

        PdfPCell cell13 = new PdfPCell(new Paragraph("文号", font));
        cell13.disableBorderSide(10);
        cell13.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell13.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(cell13);

        PdfPCell cell14 = new PdfPCell(new Paragraph(wh, font));
        cell14.disableBorderSide(2);
        table.addCell(cell14);

        PdfPCell cell21 = new PdfPCell(new Paragraph("文件标题", font));
        cell21.setLeading(1.1F, 1.1f);
        cell21.disableBorderSide(10);
        cell21.setPaddingBottom(8);
        cell21.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell21.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(cell21);

        Paragraph fileTitleP = new Paragraph(fileTitle, font);
        fileTitleP.setFirstLineIndent(12);
        PdfPCell cell22 = new PdfPCell(fileTitleP);
        cell22.setLeading(1.1F, 1.1f);
        cell22.setPaddingBottom(8);
        cell22.disableBorderSide(2);
        // 设置占用列数
        cell22.setColspan(3);
        cell22.setVerticalAlignment(Element.ALIGN_MIDDLE);
        table.addCell(cell22);

        Paragraph p = new Paragraph("厅 领 导 批 示 ", font);
        PdfPCell cell31 = new PdfPCell(p);
        int lines = getLineNum(nbyj, 32);
        if (lines <= 4) { 
            cell31.setFixedHeight(450);
        } else { 
          cell31.setFixedHeight( 450- (lines-4)*22);
        }
        cell31.disableBorderSide(10);
        cell31.setLeading(1.2F, 1.2f);
        cell31.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell31.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(cell31);

        PdfPCell cell32 = new PdfPCell(new Paragraph(tldps, font));
        cell32.setColspan(3);
        cell32.disableBorderSide(2);
        table.addCell(cell32);


        PdfPCell cell41 = new PdfPCell(new Paragraph("拟 办 意 见 ", font));
        cell41.setLeading(1.2F, 1.2f);
        cell41.disableBorderSide(8);
        cell41.setPaddingBottom(10f);
// cell41.setFixedHeight(80);
        cell41.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell41.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(cell41);

        PdfPCell cell42 = new PdfPCell(new Paragraph(nbyj, font));
        cell42.setColspan(3);
        cell42.setLeading(1.4F, 1.4f);
        cell42.setPaddingBottom(10);
        table.addCell(cell42);


        document.add(table);

        //底部
        PdfPTable t3 = new PdfPTable(3);
        // 设置表格默认为无边框
        t3.getDefaultCell().setBorder(0);
        // 设置表格上面空白宽度
        t3.setSpacingBefore(2f);
        // 设置表格宽度比例为%100
        t3.setWidthPercentage(88);
        // 设置表格的宽度
        t3.setTotalWidth(500);
        // 也可以每列分别设置宽度
        t3.setTotalWidth(new float[]{ 80, 120, 200});

        PdfPCell c1 = new PdfPCell(new Paragraph("审核:", font));
        c1.setBorder(0);
        t3.addCell(c1);

        PdfPCell c2 = new PdfPCell(new Paragraph("承办:", font));
        c2.setVerticalAlignment(Element.ALIGN_MIDDLE);
        c2.setBorder(0);
        c2.setHorizontalAlignment(Element.ALIGN_CENTER);
        t3.addCell(c2);


        PdfPCell c3 = new PdfPCell(new Paragraph("联系电话:", font));
        c3.setVerticalAlignment(Element.ALIGN_MIDDLE);
        c3.setHorizontalAlignment(Element.ALIGN_CENTER);
        c3.setBorder(0);
        t3.addCell(c3);


        document.add(t3);


        document.close();


        //图片水印
        PdfReader reader = new PdfReader(filePath);
        String result = "E:\\work\\idea\\project\\pdf\\src\\main\\resources\\r_" + System.currentTimeMillis() + ".pdf";
        PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(result));
        Image img = Image.getInstance("E:\\work\\idea\\project\\pdf\\src\\main\\resources\\jijian.png");
        img.setAbsolutePosition(500, 780);
        img.scaleToFit(600, 44);//大小
        PdfContentByte under = stamp.getUnderContent(1);
        under.addImage(img);

        stamp.close();
        reader.close();
        File file = new File(filePath);
        if (file.exists()) { 
            file.delete();
        }
        return result;
    }

    public static int getLineNum(String text, double lineWord) { 
        String[] split = text.split("\n");
        int num = 0;
        System.out.println(text.length());
        for (int i = 0; i < split.length; i++) { 
            String s = split[i];
            num += Math.ceil(s.length() / lineWord);
        }
        System.out.println(num);
        return num;
    }
}```


### 删除PDF指定页

```java
public static void removePageFromPDF(String path, String tempPath, int page) throws InterruptedException, Exception { 
        PdfReader reader = new PdfReader(path);
        File tmpNewFile = new File(tempPath);
        FileOutputStream fos = new FileOutputStream(tmpNewFile);
        com.itextpdf.text.Document d = new com.itextpdf.text.Document();
        PdfCopy copy = new PdfCopy(d, fos);
        d.open();
        for (int i = 1; i <= reader.getNumberOfPages(); ++i) { 
            if (i != page) { 
                copy.addPage(copy.getImportedPage(reader, i));
            }
        }
        copy.freeReader(reader);
        reader.close();
        d.close();
        fos.close();
    }

PDF合并

public static void mergePdfFiles(String[] files, String savepath) { 
        try { 
            PdfReader pdfReader = new PdfReader(files[0]);
            Rectangle pageSize = pdfReader.getPageSize(1);

            Document document = new Document(pageSize);

            PdfCopy copy = new PdfCopy(document, new FileOutputStream(savepath));

            document.open();

            for (int i = 0; i < files.length; i++) { 
                PdfReader reader = new PdfReader(files[i]);

                int n = reader.getNumberOfPages();

                for (int j = 1; j <= n; j++) { 
                    document.newPage();
                    PdfImportedPage page = copy.getImportedPage(reader, j);
                    copy.addPage(page);
                }
                reader.close();
            }

            pdfReader.close();
            copy.close();
            document.close();
            for (String file : files) { 
                deleteFile(file);
            }
        } catch (IOException e) { 
            e.printStackTrace();
        } catch (DocumentException e) { 
            e.printStackTrace();
        }
    }
    原文作者:小强_程序猿_
    原文地址: https://blog.csdn.net/u014389362/article/details/107940038
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。

相关文章