六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 71|回复: 0

java对pdf一些基本处理

[复制链接]

升级  27.33%

21

主题

21

主题

21

主题

秀才

Rank: 2

积分
91
 楼主| 发表于 2013-2-3 14:38:54 | 显示全部楼层 |阅读模式
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包
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表