How to save converted file to byte array

Hi, is there a way to save converted document into a byte array? I need to read in a RTF file and converted it into PDF format and pass the result back as a byte array. Thank you!

Hi Jiebo,
Thanks for your inquiry.
Sure, please see the code below:

Document doc = new Document("Document.rtf");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
doc.saveToPdf(0, doc.getPageCount(), stream, null);
byte[] bytes = stream.toByteArray();

If you need any futher assitance, please feel free to ask.
Thanks,

Hi Adam,
The code you provided works great. Thank you.
I have another question: after converting a rtf file into pdf, is there a way tell how many pages are there in the pdf document?
Thanks,

Hello

Thank for your inquiry. You can use PageCount property, please see the following code:

// Open document
Document doc = new Document("C:\\Temp\\template.doc");
// Convert to PDF
doc.saveToPdf("C:\\Temp\\out.pdf");
// Get page count
System.out.print("PageCount= " + doc.getPageCount());

Best regards,

Hi, I am trying to append a document to the end of the first document. But it seems the appending is not work. Am I missing something? thank you.

Document doc2 = new Document(new ByteArrayInputStream(inputByteDoc2));
Document doc = new Document(new ByteArrayInputStream(inputByte));
doc.appendDocument(doc2, ImportFormatMode.KEEP_SOURCE_FORMATTING);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
doc.saveToPdf(0, doc.getPageCount(), stream, null);
byte[] outputByte = stream.toByteArray();

Hi

Thanks for your inquiry. The code should work properly. The problem might occur if you call updatePageLayout before appending the document. You can try using the following code and see if this helps:

Document doc2 = new Document(new ByteArrayInputStream(inputByteDoc2));
Document doc = new Document(new ByteArrayInputStream(inputByte));
doc.appendDocument(doc2, ImportFormatMode.KEEP_SOURCE_FORMATTING);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
doc.updatePageLayout();
doc.saveToPdf(0, doc.getPageCount(), stream, null);
byte[] outputByte = stream.toByteArray();

Hope this helps. If not, Please attach your documents here for testing.
Best regards.

Hi, adding doc.updatePageLayout(); as you suggested worked.Thank you!