In my maven project I have PDF file which is located inside resources
folder. My function reads the PDF file from the resources
folder and adds some values in the document based on the user data.
This project is packed as .jar
file using mvn clean install
and is used as dependency in my other spring boot application.
When I in my spring boot project create instace of the class that will perform some work on the PDF then theproblem is that the PDF file is always empty. I have impression that mvn clean install does something with the PDF file. Here is what I've tried so far:
First way
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
File file= new ClassPathResource("/pdfs/testpdf.pdf").getFile();//Try to get PDF file
PDDocument pdf = PDDocument.load(file);//Load PDF document from the file
List<PDField> fields = forms.getFields();//Get input fields that I want to update in the PDF
fieldsMap.forEach(throwingConsumerWrapper((field,value) -> changeField(fields,field,value)));//Set input field values
pdf.save(byteArrayOutputStream);//Save value to the byte array
This works great, but as soon as I pack my project in .jar
file then I get exception that new ClassPathResource("/pdfs/testpdf.pdf").getFile();
. File class can't access anything inside .jar file (it can access .jar itself only). The solution to that problem is to use InputStream
. Here is what I have:
Second way
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
InputStream inputStream = new ClassPathResource("/pdfs/testpdf.pdf").getInputStream();//Try to get PDF file
PDDocument pdf = PDDocument.load(inputStream );//Load PDF document from the file
List<PDField> fields = forms.getFields();//Get input fields that I want to update in the PDF
fieldsMap.forEach(throwingConsumerWrapper((field,value) -> changeField(fields,field,value)));//Set input field values
pdf.save(byteArrayOutputStream);//Save value to the byte array
This time getInputStream()
doesn't throw error and inputStream object is not null. But the pdf object, once saved is empty (only one page which is empty/blank).
I even tried to compy complete inputStream and saving it to the file byte by byte but what I've noticed that every byte is equal 0. Here is what I did:
Third way
InputStream inputStream = new ClassPathResource("/pdfs/finanzamtbescheinigung.pdf").getInputStream();
Files.copy(inputStream, Paths.get("C:\\Users\\user\\Desktop\\pfds\\test.pdf"));
Copied test.pdf
is saved but when opened with Adobe Reader is reported as corrupted.
Anyone have idea how to fix this?