简体   繁体   English

使用pdfbox将pdf转换为byte [],反之亦然

[英]Convert pdf to byte[] and vice versa with pdfbox

I've read the documentation and the examples but I'm having a hard time putting it all together. 我已经阅读了文档和示例,但我很难将它们放在一起。 I'm just trying to take a test pdf file and then convert it to a byte array then take the byte array and convert it back into a pdf file then create the pdf file onto disk. 我只是试图获取一个测试pdf文件,然后将其转换为字节数组,然后获取字节数组并将其转换回pdf文件,然后将pdf文件创建到磁盘上。

It probably doesn't help much, but this is what I've got so far: 它可能没什么用,但这是我到目前为止所得到的:

package javaapplication1;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import org.apache.pdfbox.cos.COSStream;
import org.apache.pdfbox.exceptions.COSVisitorException;
import org.apache.pdfbox.pdmodel.PDDocument;

public class JavaApplication1 {

    private COSStream stream;

    public static void main(String[] args) {
        try {
            PDDocument in = PDDocument.load("C:\\Users\\Me\\Desktop\\JavaApplication1\\in\\Test.pdf");
            byte[] pdfbytes = toByteArray(in);
            PDDocument out;
        } catch (Exception e) {
            System.out.println(e);
        }
    }

    private static byte[] toByteArray(PDDocument pdDoc) throws IOException, COSVisitorException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            pdDoc.save(out);
            pdDoc.close();
        } catch (Exception ex) {
            System.out.println(ex);
        }
        return out.toByteArray();
    }

    public void PDStream(PDDocument document) {
        stream = new COSStream(document.getDocument().getScratchFile());
    }
}

You can use Apache commons , which is essential in any java project IMO. 您可以使用Apache commons ,这在任何Java项目IMO中都是必不可少的。

Then you can use FileUtils 's readFileToByteArray(File file) and writeByteArrayToFile(File file, byte[] data) . 然后你可以使用FileUtilsreadFileToByteArray(File file)writeByteArrayToFile(File file, byte[] data)

(here is commons-io, which is where FileUtils is: http://commons.apache.org/proper/commons-io/download_io.cgi ) (这里是commons-io,这是FileUtils的地方: http//commons.apache.org/proper/commons-io/download_io.cgi

For example, I just tried this here and it worked beautifully. 例如,我在这里试过这个并且效果很好。

try {
    File file = new File("/example/path/contract.pdf");
    byte[] array = FileUtils.readFileToByteArray(file);
    FileUtils.writeByteArrayToFile(new File("/example/path/contract2.pdf"), array);

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM