Need help verifying a PDF exists from a URL - java

My goal is to verify that a link to a PDF loads properly. I'm new to selenium, java, etc.
I tried both with URL and FILE after the load
PDDocument doc = PDDocument.load(new FILE ("https://xxxxxcx/iPledgeUI/rems/pdf/resources/iPledge_REMS_Non_Compliance_Action_Policy.pdf"));
PDFTextStripper pdfStripper = new PDFTextStripper();
String text = pdfStripper.getText(doc);
doc.close();
Expected result would be that the file gets loaded from the URL
Here is what I am getting
https:/xxxxxxxx/iPledgeUI/rems/pdf/resources/iPledge_REMS_Non_Compliance_Action_Policy.pdf (No such file or directory)

That isn't a file, that is an URL. Load these with
import java.net.URL;
import java.io.InputStream;
…
InputStream is = new URL("....").openStream(); // will throw here if URL doesn't work
PDDocument doc = PDDocument.load(is); // will throw here if PDF malformed or empty file
…
is.close();
If the URL doesn't exist you'll get an exception. (Exception handling code not included here)

Related

Apache POI convert HTML/XHTML to DOC/DOCX

I need to transform HTML to a doc file, the HTML is filled with custom information and the images and CSS change depending on what is request.
I'm trying to use Apache POI for this, but I'm having an error
`
org.apache.poi.xwpf.converter.core.XWPFConverterException: java.lang.IllegalStateException: Expecting one Styles document part, but found 0
at org.apache.poi.xwpf.converter.xhtml.XHTMLConverter.convert(XHTMLConverter.java:72)
at org.apache.poi.xwpf.converter.xhtml.XHTMLConverter.doConvert(XHTMLConverter.java:58)
at org.apache.poi.xwpf.converter.xhtml.XHTMLConverter.doConvert(XHTMLConverter.java:38)
at org.apache.poi.xwpf.converter.core.AbstractXWPFConverter.convert(AbstractXWPFConverter.java:45)
My code is this:
// Load the HTML file
//Doc file
String htmlFile = "pathToHtml/file.html";
//String htmlFile = parseHTMLTemplate(disputeLetterDetails, template, fileExtension);
//new File(htmlFile);
//File file = new FileReader(htmlFile);
Path path = Path.of(htmlFile);
OutputStream in = new FileOutputStream(htmlFile, true);
// Create a new XWPFDocument
XWPFDocument document = new XWPFDocument();
// Set up the XHTML options
XHTMLOptions options = XHTMLOptions.create().URIResolver(new FileURIResolver(new File("./images/")));
options.setExtractor(new FileImageExtractor(new File("./images/")));
// Convert the HTML to XWPFDocument
XHTMLConverter.getInstance().convert(document, in, options);
// Save the document to a .doc file
FileOutputStream out = new FileOutputStream("pathToHtml/OUT_from_XHTML_TEST.docx");
document.write(out);
out.close();
`
I want to get a docx file from an HTML file with the same styles but I'm getting this error `
org.apache.poi.xwpf.converter.core.XWPFConverterException: java.lang.IllegalStateException: Expecting one Styles document part, but found 0
at org.apache.poi.xwpf.converter.xhtml.XHTMLConverter.convert(XHTMLConverter.java:72)
at org.apache.poi.xwpf.converter.xhtml.XHTMLConverter.doConvert(XHTMLConverter.java:58)
at org.apache.poi.xwpf.converter.xhtml.XHTMLConverter.doConvert(XHTMLConverter.java:38)
at org.apache.poi.xwpf.converter.core.AbstractXWPFConverter.convert(AbstractXWPFConverter.java:45)
`

Extract PDF metadata using iText Java library

I am trying to get all the XMP metadata stream of a PDF file using the Java library to manipulate PDF files iText. The code I have written is:
package iTextExamples;
import java.io.FileOutputStream;
import java.io.IOException;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfReader;
public class ReadMetadata {
public static void main(String[] args) throws IOException {
String src = "C:\\Path\\PDF123.pdf";
PdfReader reader = new PdfReader(src);
PdfDocument doc = new PdfDocument(reader);
System.out.println(doc.getXmpMetadata());
reader.close();
}
}
The result I'm getting is NULL and I don't know why.
Unrelated to the issue of getting null, but doc.getXmpMetadata() returns a byte array. So you will not be able to print its content with
System.out.println(doc.getXmpMetadata());
Instead, you'll have to do something like:
byte[] xmp = doc.getXmpMetadata();
String xmpString = new String(xmp, StandardCharsets.UTF_8);
System.out.println(xmpString);
About the null issue:
I assume you're trying to get the document level XMP metadata. Make sure that your PDF file actually contains an XMP metadata stream. If not, null is expected.
You can verify with a PDF viewer that is able to show XMP, or with a PDF object viewer. The XMP metadata stream sits in the Metadata entry of the documents Catalog dictionary:

unable to read pdf document using selenium web driver

I am writing code to read pdf file in selenium using Java PDF Library.
I wrote my code as
URL url = new URL(str);
InputStream is=url.openStream();
BufferedInputStream fileParse=new BufferedInputStream(is);
PDDocument document=null;
document=PDDocument.load(fileParse);
String pdfContent=new PDFTextStripper().getText(document);
But I am getting error at line document=PDDocument.load(fileParse) along with
java.io.IOException: Error: End-of-File, expected line
at org.apache.pdfbox.pdfparser.BaseParser.readLine(BaseParser.java:1119)
at org.apache.pdfbox.pdfparser.COSParser.parseHeader(COSParser.java:2017)
at org.apache.pdfbox.pdfparser.COSParser.parsePDFHeader(COSParser.java:1988)
at org.apache.pdfbox.pdfparser.PDFParser.parse(PDFParser.java:269)
at org.apache.pdfbox.pdmodel.PDDocument.load(PDDocument.java:1143)
at org.apache.pdfbox.pdmodel.PDDocument.load(PDDocument.java:1040)
I need to verify the content on the pdf file .
Appreciate the help.
Thanks
Simply you can use below line of code and its working:
//Loading an existing document
File file = new File("yourPdfFilepath");
PDDocument document = PDDocument.load(file);
//Instantiate PDFTextStripper class
PDFTextStripper pdfStripper = new PDFTextStripper();
//Retrieving text from PDF document
String pdfcontent = pdfStripper.getText(document);
I hope it helps you

Apache Commons IO download only first PDF page

I'm using Java with Apache Commons-IO to download a PDF but I only want to get the first page, is there a way I can do it?
Here's the piece of code that gets the whole doc:
public void getPDF(String route) throws IOException {
URL url = new URL(route);
File file = new File("file.pdf");
FileUtils.copyURLToFile(url, file);
}
In continuation to your code, you may use a new Document to hold only first page of given PDF file.
URL url = new URL(route);
File file = new File("file.pdf");
FileUtils.copyURLToFile(url, file);
PDDocument pdDoc = PDDocument.load(file);
PDDocument document = null;
int pageNumberToRead=0;
try {
document = new PDDocument();
document.addPage((PDPage) pdDoc.getDocumentCatalog().getAllPages().get(pageNumberToRead));
document.save("basepath/first_page.pdf");
document.close();
}catch(Exception e){}

how to judge if the file is doc or docx in POI

The title may be a little confusing. The simplest method must be judging by extension name just like:
// is represents the InputStream
if (filePath.endsWith("doc")) {
WordExtractor ex = new WordExtractor(is);
text = ex.getText();
ex.close();
} else if(filePath.endsWith("docx")) {
XWPFDocument doc = new XWPFDocument(is);
XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
text = extractor.getText();
extractor.close();
}
This works in most cases. But I have found that for certain file whose extension is doc (a docx file essentially) if you open using winrar, you will find xml files. As it is known that a docx file is a zip file consists of xml files.
I believe this problem must not be rare. But I have not found any information about this. Obviously, judging by extension name to read a doc or docx is not appropriate.
In my case, I have to read a lot of files. And I will even read the doc or docx inside a compressed file, zip, 7z or even rar. Hence, I have to read content by inputStream instead of a File or something else. So how to know whether a file is .docx or .doc format from Apache POI is totally not suitable for my case with ZipInputStream.
What is the best way to judge a file is a doc or docx? I want a solution to read the content from a file which may be doc or docx. But not only just simply judge if it is a doc or docx. Apparently, ZipInpuStream is not a good method for my case. And I believe it is not a appropriate method for others either. Why do I have to judge if the file is doc or docx by an exception?
Using the current stable apache poi version 3.17 you may use FileMagic. But internally this will of course also have a look into the files.
Example:
import java.io.InputStream;
import java.io.FileInputStream;
import java.io.BufferedInputStream;
import org.apache.poi.poifs.filesystem.FileMagic;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
public class ReadWord {
static String read(InputStream is) throws Exception {
System.out.println(FileMagic.valueOf(is));
String text = "";
if (FileMagic.valueOf(is) == FileMagic.OLE2) {
WordExtractor ex = new WordExtractor(is);
text = ex.getText();
ex.close();
} else if(FileMagic.valueOf(is) == FileMagic.OOXML) {
XWPFDocument doc = new XWPFDocument(is);
XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
text = extractor.getText();
extractor.close();
}
return text;
}
public static void main(String[] args) throws Exception {
InputStream is = new BufferedInputStream(new FileInputStream("ExampleOLE.doc")); //really a binary OLE2 Word file
System.out.println(read(is));
is.close();
is = new BufferedInputStream(new FileInputStream("ExampleOOXML.doc")); //a OOXML Word file named *.doc
System.out.println(read(is));
is.close();
is = new BufferedInputStream(new FileInputStream("ExampleOOXML.docx")); //really a OOXML Word file
System.out.println(read(is));
is.close();
}
}
try {
new ZipFile(new File("/Users/giang/Documents/a.doc"));
System.out.println("this file is .docx");
} catch (ZipException e) {
System.out.println("this file is not .docx");
e.printStackTrace();
}

Categories

Resources