We have iText API in Java for working with PDF files.
To check if the PDF file is valid for downloading and reading, use com.itextpdf.text.pdf.PdfReader.
If the file is damaged, a type exception is thrown com.itextpdf.text.exceptions.InvalidPdfException.
Example code snippet :
...
import com.itextpdf.text.pdf.PdfReader;
...
try {
PdfReader pdfReader = new PdfReader( pathToUploadedPdfFile );
String textFromPdfFilePageOne = PdfTextExtractor.getTextFromPage( pdfReader, 1 );
System.out.println( textFromPdfFilePageOne );
}
catch ( Exception e ) {
}
In the case of downloaded but damaged files, the following error may occur:
com.itextpdf.text.exceptions.InvalidPdfException: Rebuild failed:
trailer not found.; Original message: PDF startxref not found.
Note. To create such an exception, try saving the PDF file from the network, but interrupt it in the middle.
Use it to download through a piece of code and check if it is securely downloaded.
You can find detailed examples in the iText API, here .
source
share