[Solved] itextpdf Read PDF File Error: Rebuild failed: trailer not found.

Recently, I used itextpdf to print invoices, but there was an error when reading the file stream. The following is the key code

ClassPathResource classPathResource = new ClassPathResource("/template/RU_HK_INVOICE_TEMPLATE.pdf");
InputStream inputStream = classPathResource.getInputStream();
reader = new PdfReader(inputStream);// read the template of pdf

The following errors are reported in the new PdfReader(inputStream) each time:

com.itextpdf.text.exceptions.InvalidPdfException: Rebuild failed: trailer not found.; Original message: xref subsection not found at file pointer

Maven will use pom XML configuration files uniformly encode the project, but some files do not need to be re encoded, such as PDF template files; After recoding, the PDF template structure may be damaged, resulting in the unavailability of the files generated after compilation, as shown in the following figure

Therefore, it is necessary to filter out the files that do not need to be encoded: filter all files with the suffix .pdf or .p8 and do not encode them uniformly. Need to be configured in the pom.xml file nonFilteredFileExtension tag

<!-- Filter the suffixes of files that do not need to be transcoded pdf -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-resources-plugin</artifactId>
                <version>3.0.1</version>
                <configuration>
                    <encoding>UTF-8</encoding>
                    <useDefaultDelimiters>false</useDefaultDelimiters>
                    <nonFilteredFileExtensions>
 						<nonFilteredFileExtension>pdf</nonFilteredFileExtension>
                    </nonFilteredFileExtensions>
                </configuration>
            </plugin>

Read More: