如何从响应中读取pdf内容,并将其写入另一个新的pdf文件


%PDF-1.4
%����
1 0 obj
<<
/Type /Catalog
/Pages 9 0 R
/Outlines 8 0 R
/Names 6 0 R

我正在尝试从java类的rest端点读取上面的pdf内容响应,并尝试将其写入另一个文件但是文件被破坏了,我无法查看pdf生成的

File file = new File("Data.pdf");-- trying to write data to this
FileOutputStream out = new FileOutputStream(file)
\service call to download pdf document
out.write(response.getBody().getBytes());

如何将pdf内容写入另一个文件或以正确的方式生成新的pdf?

基本上,您想要从InputStream读取,然后写入OutputStream。这个问题已经回答了好几次,比如这里、这里和这里,有很多可能的解决方案。由于您也标记了ioutils,一种可能的方法是:

File file = new File("Data.pdf");
FileOutputStream out = new FileOutputStream(file)
IOUtils.copy(response.getBody(), out);

这假定response.getBody返回一个InputStream。如果你提供更多的代码,我们可以肯定。(这取决于您正在使用的restclient实现,如JAX-RS、Spring Rest、Apache httpClient或HttpUrlConnection…

iText 7中的PdfReader类有一个重载版本,它将InputStream作为参数。使用这种方法,您基本上可以使用ByteArrayInputStream读取第一个输入pdf的字节数。iText 7有一个PDFWriter类,它也可以写入OutputStream。请参阅以下片段。然后,PdfDocument类可以读取输入的pdf文件,并使用pdfWriter将其写入新文件。
//Pdf bytes returned by some rest API or method
byte[] bytes = {};
ByteArrayInputStream bin = new ByteArrayInputStream(bytes);

//File where you want to write the pdf and update some content
File file = new File("Data.pdf");
FileOutputStream out = new FileOutputStream(file);

PdfDocument dd = new PdfDocument(new PdfReader(bin), new PdfWriter(out));

相关内容

最新更新