java - Convert pdf to byte[] and vice versa with pdfbox -


i've read documentation , examples i'm having hard time putting together. i'm trying take test pdf file , convert byte array take byte array , convert pdf file create pdf file onto disk.

it doesn't much, i've got 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, essential in java project imo.

then can use fileutils's readfiletobytearray(file file) , writebytearraytofile(file file, byte[] data).

(here commons-io, fileutils is: http://commons.apache.org/proper/commons-io/download_io.cgi )

for example, tried here , 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(); } 

Comments

Popular posts from this blog

php - Calling a template part from a post -

Firefox SVG shape not printing when it has stroke -

How to mention the localhost in android -