Add image as a header in XWPF document - java

How do I add a image as a header to every page in XWPF document ?
I have tried every possible thing I could think of , below is my code :
XWPFDocument docx = new XWPFDocument();
CTSectPr sectPr = docx.getDocument().getBody().addNewSectPr();
XWPFHeaderFooterPolicy policy = new XWPFHeaderFooterPolicy(docx, sectPr);
XWPFHeader header = policy.createHeader(XWPFHeaderFooterPolicy.FIRST);
String imgFile="sample.png";
header.addPictureData(new FileInputStream(imgFile), XWPFDocument.PICTURE_TYPE_PNG);
String nameoffile ="customer"+".docx";
FileOutputStream out = new FileOutputStream(nameoffile);
docx.write(out);
out.close();
However this is giving me a java.lang.IndexOutOfBoundsException at line java.lang.IndexOutOfBoundsException

You should add a correct directory for image. Probably "new FileInputStream(imgFile)" is null.
Put your image in directory then set path as:
String imgFile="C:\Users\{user}\Desktop\Project\sample.png";

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)
`

Extracted pdf text is not getting displayed in console

I am trying to extract the pdf text using Tabula. But the code has no errors but when i run the extracted pdf text does not get displayed in console. Could some one help.
I have been using PDFBox and after doing some research, i have found that tabula is new and wanted to try it.
File file = new File(pdfFilePath);
PDDocument document = PDDocument.load(file);
ObjectExtractor oe = new ObjectExtractor(document);
Page page = oe.extract(1) //1st page
TextStripper textStripper = new TextStripper(document,1);
System.out.println(textStripper.getText(document));
output of pdf text
You are not using the page variable. Try the following code.
File file = new File(pdfFilePath);
PDDocument document = PDDocument.load(file);
ObjectExtractor oe = new ObjectExtractor(document);
Page page = oe.extract(1); // 1st page
for (TextElement textElement: page.getText()) {
System.out.print(textElement.getText());
}

How to copy/move AcroForm fields from one document to new blank one using IText5 or IText7?

I need to copy whole AcroForm including field positions and values from template PDF to a new blank PDF file. How can I do that?
In short words - I need to get rid of "background" from the template and leave only filed forms.
The whole point of this is to create a PDF with content that would be printed on pre-printed templates.
I am using IText 5 but I can switch to 7 if usefull examples would be provided
After a lot of trial and error I have found the solution to "How to copy AcfroForm fields into another PDF". It is a iText v7 version. I hope it will help somebody someday.
private byte[] copyFormElements(byte[] sourceTemplate) throws IOException {
PdfReader completeReader = new PdfReader(new ByteArrayInputStream(sourceTemplate));
PdfDocument completeDoc = new PdfDocument(completeReader);
ByteArrayOutputStream out = new ByteArrayOutputStream();
PdfWriter offsetWriter = new PdfWriter(out);
PdfDocument offsetDoc = new PdfDocument(offsetWriter);
offsetDoc.initializeOutlines();
PdfPage blank = offsetDoc.addNewPage();
PdfAcroForm originalForm = PdfAcroForm.getAcroForm(completeDoc, false);
// originalForm.getPdfObject().copyTo(offsetDoc,false);
PdfAcroForm offsetForm = PdfAcroForm.getAcroForm(offsetDoc, true);
for (String name : originalForm.getFormFields().keySet()) {
PdfFormField field = originalForm.getField(name);
PdfDictionary copied = field.getPdfObject().copyTo(offsetDoc, false);
PdfFormField copiedField = PdfFormField.makeFormField(copied, offsetDoc);
offsetForm.addField(copiedField, blank);
}
offsetDoc.close();
completeDoc.close();
return out.toByteArray();
}
Did you check the PdfCopyForms object:
Allows you to add one (or more) existing PDF document(s) to create a new PDF and add the form of another PDF document to this new PDF.
I didn't find an example, but you could try something like this:
PdfReader reader1 = new PdfReader(src1); // a document with a form
PdfReader reader2 = new PdfReader(src2); // a document without a form
PdfCopyForms copy = new PdfCopyForms(new FileOutputStream(dest));
copy.AddDocument(reader1); // add the document without the form
copy.CopyDocumentFields(reader2); // add the fields of the document with the form
copy.close();
reader1.close();
reader2.close();
I see that the class is deprecated. I'm not sure of that's because iText 7 makes it much easier to do this, or if it's because there were technical problems with the class.

Adding footer to ms word using POI api

I searched a lot and getting some results in which some sample code is there but no one is working. All are either getting null pointer exception or if document is generated then at the time of opening file (.docx) giving error and displaying message
A text/xml declaration may occur only at the very beginning of innput.
I thought may be I am adding some content and then adding footer is giving some problem so I pasted my footer code at very beginning now this time I am getting
index out of bound exception
Here is my complete code
String fileName ="Book.docx";
String folderPath=SystemProperties.get(SystemProperties.TMP_DIR)+File.separator+"liferay" + File.separator + "document_preview";
String filePath=folderPath+File.separator+fileName;
File file=new File(filePath);
XWPFDocument document = new XWPFDocument();
XWPFParagraph paragraphOne = document.createParagraph();
paragraphOne.setAlignment(ParagraphAlignment.CENTER);
XWPFRun paragraphOneRunOne = paragraphOne.createRun();
paragraphOneRunOne.setText("Training Report");
paragraphOneRunOne.addBreak();
XWPFTable table = document.createTable();
XWPFTableRow tableRowOne = table.getRow(0);
tableRowOne.getCell(0).setText("No");
tableRowOne.createCell().setText("Name");
XWPFHeaderFooterPolicy headerFooterPolicy = document.getHeaderFooterPolicy();
if (headerFooterPolicy == null) {
CTBody body = document.getDocument().getBody();
CTSectPr sectPr = body.getSectPr();
if (sectPr == null) {
sectPr = body.addNewSectPr();
}
headerFooterPolicy = new XWPFHeaderFooterPolicy(document, sectPr);
}
CTP ctP1 = CTP.Factory.newInstance();
CTR ctR1 = ctP1.addNewR();
CTText t = ctR1.addNewT();
t.setStringValue("first footer");
XWPFParagraph codePara = new XWPFParagraph(ctP1);
XWPFParagraph[] newparagraphs = new XWPFParagraph[1];
newparagraphs[0] = codePara;
XWPFFooter xwpfFooter = null;
xwpfFooter = headerFooterPolicy.createFooter(XWPFHeaderFooterPolicy.DEFAULT);
FileOutputStream fileoutOfTraining = new FileOutputStream(file);
document.write(fileoutOfTraining);
fileoutOfTraining.flush();
fileoutOfTraining.close();
downloadOperation(file, fileName, resourceResponse);
code in downloadOperation method
HttpServletResponse httpServletResponse =PortalUtil.getHttpServletResponse(resourceResponse);
BufferedInputStream input = null;
BufferedOutputStream output = null;
httpServletResponse.setHeader("Content-Disposition", "attachment; filename=\""+fileName+"\"; filename*=UTF-8''"+fileName);
int DEFAULT_BUFFER_SIZE=1024;
try {
input = new BufferedInputStream(new FileInputStream(file), DEFAULT_BUFFER_SIZE);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
resourceResponse.flushBuffer();
output = new BufferedOutputStream(httpServletResponse.getOutputStream(), DEFAULT_BUFFER_SIZE);
} catch (IOException e) {
e.printStackTrace();
}
byte[] buffer = new byte[2*DEFAULT_BUFFER_SIZE];
int length;
try {
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
output.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Please help me to generate footer, this is my code, if I add footer code after my paragraph and table then no run time error but error in opening generated file, if I placed footer at before the contents that I want to add in documents then I am getting error "index out of bound exception".
Please help me if any one having any code snippet or at least some pointers towards the solution.
Thanks
I faced this issue and the solution is
We have to use 3.10 final poi jar.
3.9 having this problem.
Please remove jars of previous version and add jars of 3.10 final version in which this bug is fixed.
Jars requires are:
poi-3.10-FINAL.jar
poi-ooxml-3.10-FINAL.jar
poi-ooxml-schemas-3.10-FINAL.jar
Easily available in net:
http://mvnrepository.com/artifact/org.apache.poi/poi/3.10-FINAL
XWPFDocument document = new XWPFDocument();
CTP ctp = CTP.Factory.newInstance();
CTR ctr = ctp.addNewR();
CTRPr rpr = ctr.addNewRPr();
CTText textt = ctr.addNewT();
textt.setStringValue( " Page 1" );
XWPFParagraph codePara = new XWPFParagraph( ctp, document );
XWPFParagraph[] newparagraphs = new XWPFParagraph[1];
newparagraphs[0] = codePara;
CTSectPr sectPr = document.getDocument().getBody().addNewSectPr();
XWPFHeaderFooterPolicy headerFooterPolicy = new XWPFHeaderFooterPolicy( document, sectPr );
headerFooterPolicy.createFooter( STHdrFtr.DEFAULT, newparagraphs );
The above code is working perfectly, please use 3.10 wars those I mentioned above.
I don't know if adding image to header from scratch works in new version, but I know for a fact that "templating" works just perfectly. I created the template document in word, adapted the header the way I needed it to be (in my case, logo-image was on the right, paragraph with dummy text on the left, and another image that separates the upper two objects from the content, on the header bottom, and all was repeating on all the pages) and left the rest of the document empty. On the very beginning, I didn't create the XWPFDocument by calling the ...new XWPFDocument() anymore, I created it this way:
XWPFDocument doc = new XWPFDocument(new FileInputStream("pathTo/template.docx"));
Than just fill your document with your content, and if you need to update the header text for different exports like I did, call the update header function, that in my case looks something like this:
public void updateHeader() throws InvalidFormatException, IOException {
// load the header policy from template and update the paragraph text
XWPFHeaderFooterPolicy headerFooterPolicy = document
.getHeaderFooterPolicy();
XWPFHeader defaultHeader = headerFooterPolicy.getDefaultHeader();
defaultHeader.getParagraphs().get(0).getRuns().get(0)
.setText(profileName, 0);
// this is only to put some space between the content in the header and the real content
defaultHeader.getParagraphs()
.get(defaultHeader.getParagraphs().size() - 1)
.setSpacingAfter(300);
}
As far as I know, this works since 3.10, and if you stumble upon some java security issues, try the current nightly version where many of these security issues were resolved. For me it even worked on Google App Engine.

Set word document page margins through java

I have created a file by using Java where I want to change page margins but I can't
Here is my code:
XWPFDocument document = new XWPFDocument();
XWPFParagraph paragraph = document.createParagraph();
XWPFRun run = paragraph.createRun();
paragraph.setAlignment(ParagraphAlignment.LEFT);
paragraph.setNumID(BigInteger.ONE);
run.setFontSize(18);
run.setText("Test");
try{
FileOutputStream output = new FileOutputStream("C://WordDocument.docx");
document.write(output);
output.close();
} catch (Exception e){
e.printStackTrace();
}
What I want to do is something like document.setMarginLeft( Left_Margin ); and document.setMarginRight( Right_Margin );
Thanks in advance
I think he/she meant for ooxml-schemas library and rest dependencies.
you need to get the body of the document and adding a Section, then adding a CTPageMar, this object proovide methods for setting margins for the section you just created.
this is actually working for me,
values are large i suppose 10000 is the total width of a page but i'm not sure about it, so find your own desidered values :)
XWPFDocument doc = new XWPFDocument();
CTSectPr sectPr = doc.getDocument().getBody().addNewSectPr();
CTPageMar pageMar = sectPr.addNewPgMar();
pageMar.setLeft(BigInteger.valueOf(1500L));
pageMar.setRight(BigInteger.valueOf(1500L));
pageMar.setTop(BigInteger.valueOf(2000L));
pageMar.setBottom(BigInteger.valueOf(1000L));
enjoy

Categories

Resources