java对pdf一些基本处理

apahce 孵化器中有一个项目是pdfbox,这是一个操作处理pdf的jar包

可以实现的方法有
pdf信息提取:
    public void getContent(String file) throws Exception {
        PDDocument pdf = PDDocument.load(file);
        PDFTextStripper s = new PDFTextStripper();
        s.setStartPage(1);
        s.setEndPage(10);
        String outfile = "1.txt";
        Writer out = new OutputStreamWriter(new FileOutputStream(outfile), "utf8");
        s.writeText(pdf, out);
    }

将pdf内容提取到txt文档中,不过图表、格式都有遗失

pdf截取
    @SuppressWarnings("unchecked")
    public void getPdf(String file, int[] pages) throws Exception {
        Splitter splitter = new Splitter();
        PDDocument document = null;
        List<PDDocument> documents = null;
        document = PDDocument.load(file);
        splitter.setSplitAtPage(1);// 将pdf分成单页
        documents = splitter.split(document);
        for (int i = 0; i < pages.length && pages[i] < documents.size(); i++) {
            PDDocument doc = (PDDocument) documents.get(pages[i]);
            FileOutputStream output = null;
            COSWriter writer = null;
            output = new FileOutputStream(pages[i] + ".pdf");// 输出文件
            writer = new COSWriter(output);
            writer.write(doc);
            doc.close();
        }
    }

提取特定页码的pdf,例如pages=[1,2,3,4,5],将输出五个pdf文件,分别为原pdf的前五页。

pdf粘合
    public void buildPdf(String[] files) throws Exception {
        PDFMergerUtility u = new PDFMergerUtility();
        PDDocument out = new PDDocument();
        for (int i = 0; i < files.length; i++) {
            PDDocument doc = PDDocument.load(files[i]);
            u.appendDocument(out, doc);
            doc.close();
        }
        FileOutputStream output = null;
        COSWriter writer = null;
        output = new FileOutputStream("out.pdf");// 输出文件
        writer = new COSWriter(output);
        writer.write(out);
        out.close();
    }

将几个pdf拼成一个新的pdf

pdf截取和pdf粘合都不会丢失图表、格式等信息

附上所需jar包

你可能感兴趣的:(java)