Apache PDFBox

  • 主要功能:创建、提取文本,分割 / 合并 / 删除 …
  • 主要类:
  • PDDocument PDF文档对象
  • PDFTextStripper PDF文本对象
  • PDFMergerUtility 合并工具

写入PDF文件

public static void main(String[] args) {
    createPDFFile();
}
@SuppressWarnings("all")
public static void createPDFFile() {
    PDDocument doc = null;
    PDPage page = null;

    try {
        doc = new PDDocument();
        page = new PDPage(PDRectangle.A4);
        // 导入外部字体
        PDFont font =  PDType0Font.load(doc, new File("D:\\PingFang Bold.ttf"));
        PDPageContentStream content = new PDPageContentStream(doc, page);
        page.getResources().add(font);
        // 给PDF添加一页
        doc.addPage(page);
        // 设置字体
        content.setFont(font, 12);
        // 开始设置文本
        content.beginText();
        content.moveTextPositionByAmount(100, 700);
        content.showText("你好,世界");

        // 结束设置文本
        content.endText();
        content.close();
        // PDF保存
        doc.save("test.pdf");
        doc.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

注意: 当写入中文时需要导入外部字体包,否则会报U+4F60 (’.notdef’) is not available in this font Helvetica-Bold encoding: WinAnsiEncoding 错误

读取PDF文件

public static void main(String[] args) {
    readPDFFile();
}

public static void readPDFFile() {
    File pdfFile = new File("test.pdf");
    try {
        PDDocument doc = PDDocument.load(pdfFile);
        // 判断是否有权限访问文本
        AccessPermission permission = doc.getCurrentAccessPermission();
        boolean notAccess = ! permission.canExtractContent();
        if (notAccess) {
            throw new IOException("无权限访问");
        }

        // 获取页码
        int pages = doc.getNumberOfPages();
        // 读取文本内容
        PDFTextStripper stripper = new PDFTextStripper();
        // 设置按顺序输出
        stripper.setSortByPosition(true);
        // 起始页
        stripper.setStartPage(1);
        stripper.setEndPage(pages);
        String content = stripper.getText(doc);
        System.out.println(content);

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

合并PDF

public static void main(String[] args) throws Exception {
    merge();
}
public static void merge() throws Exception {
    FileOutputStream fos =
            new FileOutputStream(
            new File("merge.pdf"));
    ByteArrayOutputStream merge = null;
    File file1 = new File("E:\\TangJiachang\\java学习\\MavenDemo\\test.pdf");
    File file2 = new File("E:\\TangJiachang\\java学习\\MavenDemo\\test1.pdf");

    List<InputStream> list = new ArrayList<>();
    try {
        list.add(new FileInputStream(file1));
        list.add(new FileInputStream(file2));
        merge = new ByteArrayOutputStream();

        // 设置来源和目标
        PDFMergerUtility pdfMerger = new PDFMergerUtility();
        pdfMerger.addSources(list);
        pdfMerger.setDestinationStream(merge);

        // 设置合并选项
        PDDocumentInformation pdfDocumentInfo = new PDDocumentInformation();
        pdfMerger.setDestinationDocumentInformation(pdfDocumentInfo);

        // 合并
        pdfMerger.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly());

        fos.write(merge.toByteArray());
        fos.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}