java 使用 pdfbox 将 pdf 转换为 byte[],反之亦然
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17708200/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert pdf to byte[] and vice versa with pdfbox
提问by ThreaT
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());
}
}
回答by Doodad
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)
.
然后你可以使用文件实用程序的 readFileToByteArray(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();
}