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.
Related
I'm trying to copy a certain number of paragraphs from an ms word file into a new one with Apache Poi. Although I copy paragraph styles without problem but I can't transfer inline character styles to new file, how to get and apply character styles to new new doc?
FileInputStream in = new FileInputStream("oldDoc.docx");
XWPFDocument doc = new XWPFDocument(in);
XWPFDocument newDoc = new XWPFDocument();
// Copy styles from old to new doc
XWPFStyles newStyles = newDoc.createStyles();
newStyles.setStyles(doc.getStyle());
List<XWPFParagraph> paragraphs = doc.getParagraphs();
for (int p = 0; p < paragraphs.size(); p++) {
XWPFParagraph oldPar = paragraphs.get(p);
XWPFParagraph newPar = newDoc.createParagraph();
// Apply paragraph style
newPar.setStyle(oldPar.getStyle());
XWPFRun run = newPar.createRun();
run.setText(oldPar.getText());
}
FileOutputStream outNewDoc = new FileOutputStream("newDoc.docx");
newDoc.write(outNewDoc);
in.close();
outNewDoc.close();
try {
FileInputStream in = new FileInputStream("in.docx");
XWPFDocument oldDoc = new XWPFDocument(in);
XWPFDocument newDoc = new XWPFDocument();
// Copy styles from template to new doc
XWPFStyles newXStyles = newDoc.createStyles();
newXStyles.setStyles(oldDoc.getStyle());
List<XWPFParagraph> oldDocParagraphs = oldDoc.getParagraphs();
for (XWPFParagraph oldPar : oldDocParagraphs) {
// Create new paragraph and set it style of old paragraph
XWPFParagraph newPar = newDoc.createParagraph();
newPar.setStyle(oldPar.getStyle());
// Loop in runs of old paragraphs.
for (XWPFRun oldRun : oldPar.getRuns()) { // Paragrafın sitillere göre parçalanmış stringleri
// Create a run for the new paragraph
XWPFRun newParRun = newPar.createRun();
// Set old run's text of old paragraph to the run of new paragraph
String runText = oldRun.text();
newParRun.setText(runText);
// Set old run's style of old paragraph to the run of new paragraph
CTRPr oldCTRPr = oldRun.getCTR().getRPr();
if (oldCTRPr != null) {
if (oldCTRPr.sizeOfRStyleArray() != 0){
String carStyle = oldRun.getStyle();
newParRun.setStyle(carStyle);
}
}
// Add the new run to the new paragraph
newPar.addRun(newParRun);
}
// Write to file and close.
FileOutputStream out = new FileOutputStream("out.docx");
newDoc.write(out);
out.close();
}
} catch (IOException | XmlException e) {
e.printStackTrace();
}
i'm using iText 5.5.5 with Java5.
I'm trying to merge some PDF/A. when I got a "PdfAConformanceException: PDF array is out of bounds".
Trying to find error I find the "bad PDF" that cause the error and when I try to copy just it exception throw again. This error don't appear always, it appear just when this PDF/A is in the "job chain"; I tried with some other files and it's all fine. I cant share with you source PDF 'couse it's restricted.
That's my piece of code:
_log.info("Start Document Merge");
// Output pdf
ByteArrayOutputStream bos = new ByteArrayOutputStream();
com.itextpdf.text.Document document = new com.itextpdf.text.Document();
PdfCopy copy = new PdfACopy(document, bos, PdfAConformanceLevel.PDF_A_1B);
PageStamp stamp = null;
PdfReader reader = null;
PdfContentByte content = null;
int outPdfPageCount = 0;
BaseFont baseFont = BaseFont.createFont("Arial", BaseFont.WINANSI, BaseFont.EMBEDDED);
copyOutputIntents(reader, copy);
// Loop over the pages in that document
try {
int numberOfPages = reader.getNumberOfPages();
for (int i = 1; i <= numberOfPages; i++) {
PdfImportedPage pagecontent = copy.getImportedPage(reader, i);
_log.debug("Handling page numbering [" + i + "]");
stamp = copy.createPageStamp(pagecontent);
content = stamp.getUnderContent();
content.beginText();
content.setFontAndSize(baseFont, Configuration.NumPagSize);
content.showTextAligned(PdfContentByte.ALIGN_CENTER, String.format("%s %s ", Configuration.NumPagPrefix, i), Configuration.NumPagX, Configuration.NumPagY, 0);
content.endText();
stamp.alterContents();
copy.addPage(pagecontent);
outPdfPageCount++;
if (outPdfPageCount > Configuration.MaxPages) {
_log.error("Pdf Page Count > MaxPages");
throw new PackageException(Constants.ERROR_104_TEXT, Constants.ERROR_104);
}
}
copy.freeReader(reader);
reader.close();
copy.createXmpMetadata();
document.close();
} catch (Exception e) {
_log.error("Error during mergin Document, skip");
_log.debug(MiscUtil.stackToString(e));
}
return bos.toByteArray();
That's the full stacktrace:
com.itextpdf.text.pdf.PdfAConformanceException: PDF array is out of bounds.
at com.itextpdf.text.pdf.internal.PdfA1Checker.checkPdfObject(PdfA1Checker.java:269)
at com.itextpdf.text.pdf.internal.PdfAChecker.checkPdfAConformance(PdfAChecker.java:208)
at com.itextpdf.text.pdf.internal.PdfAConformanceImp.checkPdfIsoConformance(PdfAConformanceImp.java:71)
at com.itextpdf.text.pdf.PdfWriter.checkPdfIsoConformance(PdfWriter.java:3480)
at com.itextpdf.text.pdf.PdfWriter.checkPdfIsoConformance(PdfWriter.java:3476)
at com.itextpdf.text.pdf.PdfArray.toPdf(PdfArray.java:165)
at com.itextpdf.text.pdf.PdfDictionary.toPdf(PdfDictionary.java:149)
at com.itextpdf.text.pdf.PdfArray.toPdf(PdfArray.java:175)
at com.itextpdf.text.pdf.PdfDictionary.toPdf(PdfDictionary.java:149)
at com.itextpdf.text.pdf.PdfIndirectObject.writeTo(PdfIndirectObject.java:158)
at com.itextpdf.text.pdf.PdfWriter$PdfBody.write(PdfWriter.java:420)
at com.itextpdf.text.pdf.PdfWriter$PdfBody.add(PdfWriter.java:398)
at com.itextpdf.text.pdf.PdfWriter$PdfBody.add(PdfWriter.java:373)
at com.itextpdf.text.pdf.PdfWriter$PdfBody.add(PdfWriter.java:369)
at com.itextpdf.text.pdf.PdfWriter.addToBody(PdfWriter.java:843)
at com.itextpdf.text.pdf.PdfCopy.addToBody(PdfCopy.java:839)
at com.itextpdf.text.pdf.PdfCopy.addToBody(PdfCopy.java:821)
at com.itextpdf.text.pdf.PdfCopy.copyIndirect(PdfCopy.java:426)
at com.itextpdf.text.pdf.PdfCopy.copyIndirect(PdfCopy.java:446)
at com.itextpdf.text.pdf.PdfCopy.copyObject(PdfCopy.java:577)
at com.itextpdf.text.pdf.PdfCopy.copyDictionary(PdfCopy.java:503)
at com.itextpdf.text.pdf.PdfCopy.copyObject(PdfCopy.java:573)
at com.itextpdf.text.pdf.PdfCopy.copyDictionary(PdfCopy.java:503)
at com.itextpdf.text.pdf.PdfCopy.copyObject(PdfCopy.java:573)
at com.itextpdf.text.pdf.PdfCopy.copyDictionary(PdfCopy.java:493)
at com.itextpdf.text.pdf.PdfCopy.copyDictionary(PdfCopy.java:519)
at com.itextpdf.text.pdf.PdfCopy.addPage(PdfCopy.java:663)
at com.itextpdf.text.pdf.PdfACopy.addPage(PdfACopy.java:115)
at it.m2sc.engageone.documentpackage.generator.PackageGenerator.mergePDF(PackageGenerator.java:256)
In that specific case, the problem depends by a specific Font ( Gulim ) that is too big to be embedded in PDF/A-1 file. When that font was removed, everything war run fine.
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
I would like to create a header for docx document using apache poi but I have difficulties. I have no working code to show. I would like to ask for some piece of code as starting point.
There's an Apache POI Unit test that covers your very case - you're looking for TestXWPFHeader#testSetHeader(). It covers starting with a document with no headers or footers set, then adding them
Your code would basically be something like:
XWPFHeaderFooterPolicy policy = sampleDoc.getHeaderFooterPolicy();
if (policy.getDefaultHeader() == null && policy.getFirstPageHeader() == null
&& policy.getDefaultFooter() == null) {
// Need to create some new headers
// The easy way, gives a single empty paragraph
XWPFHeader headerD = policy.createHeader(policy.DEFAULT);
headerD.getParagraphs(0).createRun().setText("Hello Header World!");
// Or the full control way
CTP ctP1 = CTP.Factory.newInstance();
CTR ctR1 = ctP1.addNewR();
CTText t = ctR1.addNewT();
t.setStringValue("Paragraph in header");
XWPFParagraph p1 = new XWPFParagraph(ctP1, sampleDoc);
XWPFParagraph[] pars = new XWPFParagraph[1];
pars[0] = p1;
policy.createHeader(policy.FIRST, pars);
} else {
// Already has a header, change it
}
See the XWPFHeaderFooterPolicy JavaDocs for a bit more on creating headers and footers.
It isn't the nicest, so it could ideally use some kind soul submitting a patch to make it nicer (hint hint...!), but it can work as the unit tests show
Based on the previous answer, just copy and paste:
public void test1() throws IOException{
XWPFDocument sampleDoc = new XWPFDocument();
XWPFHeaderFooterPolicy policy = sampleDoc.getHeaderFooterPolicy();
//in an empty document always will be null
if(policy==null){
CTSectPr sectPr = sampleDoc.getDocument().getBody().addNewSectPr();
policy = new XWPFHeaderFooterPolicy( sampleDoc, sectPr );
}
if (policy.getDefaultHeader() == null && policy.getFirstPageHeader() == null
&& policy.getDefaultFooter() == null) {
XWPFHeader headerD = policy.createHeader(policy.DEFAULT);
headerD.getParagraphs().get(0).createRun().setText("Hello Header World!");
}
FileOutputStream out = new FileOutputStream(System.currentTimeMillis()+"_test1_header.docx");
sampleDoc.write(out);
out.close();
sampleDoc.close();
}
I want to generate a PDF of questions and their options using iText. I am able to generate the PDF but the problem is sometimes questions get printed at the end of a page and options go to the next page.
How can I determine that a question and its option will not fit in the same page?
This means that if question and options will not fit in the same page then that they must be placed on the next page.
UPDATED
com.itextpdf.text.Document document = new com.itextpdf.text.Document(PageSize.A4,50,50,15,15);
ByteArrayOutputStream OutputStream = new ByteArrayOutputStream();
PdfWriter writer = PdfWriter.getInstance(document, OutputStream);
document.open();
Paragraph paragraph = new Paragraph("Paper Name Here",new Font(FontFamily.TIMES_ROMAN,15,Font.BOLD));
paragraph.setAlignment(Element.ALIGN_CENTER);
document.add(paragraph);
document.addTitle("Paper Name Here");
document.addAuthor("corp");
com.itextpdf.text.List list = new com.itextpdf.text.List(true);
for (long i = 1; i <= 20 ; i++)
{
List<MultipleChoiceSingleCorrect> multipleChoiceSingleCorrects = new MultipleChoiceSingleCorrectServicesImpl().getItemDetailsByItemID(i);
for (MultipleChoiceSingleCorrect multipleChoiceSingleCorrect : multipleChoiceSingleCorrects) {
list.add(multipleChoiceSingleCorrect.getItemText());
RomanList oplist = new RomanList();
oplist.setIndentationLeft(20);
for (OptionSingleCorrect optionSingleCorrect : multipleChoiceSingleCorrect.getOptionList()) {
oplist.add(optionSingleCorrect.getOptionText());
}
list.add(oplist);
}
}
document.add(list);
document.close();
after this I m getting abnormal page brakes means some times question is at end of page and option jumps to next page.(AS shown in image below)
What you are interested in are the setKeepTogether(boolean) methods :
for Paragraph
or for PdfPTable
This will keep the object in one page, forcing the creation of a new page if the content doesn't fit in the remaining page.
with the help of Alexis Pigeon I done with this code. So special thanks to him.
I have added question text to Paragraph after that all options kept in an list.
Option list opList added in paragraph, this paragraph add to an ListItem and this ListItem
added to an master list.
This way question splitting on two pages is resolved but I m not getting question numbers.. I already set master list as numbered=true com.itextpdf.text.List list = new com.itextpdf.text.List(true);
Code:-
try {
String Filename="PaperName.pdf";
com.itextpdf.text.Document document = new com.itextpdf.text.Document(PageSize.A4,50,50,15,15);
ByteArrayOutputStream OutputStream = new ByteArrayOutputStream();
PdfWriter writer = PdfWriter.getInstance(document, OutputStream);
document.open();
Paragraph paragraph = new Paragraph("Paper Name Here",new Font(FontFamily.TIMES_ROMAN,15,Font.BOLD));
paragraph.setAlignment(Element.ALIGN_CENTER);
paragraph.setSpacingAfter(20);
document.add(paragraph);
document.addTitle("Paper Name Here");
document.addAuthor("crop");
document.addCreator("crop");
com.itextpdf.text.List list = new com.itextpdf.text.List(true);
for (long i = 1; i <= 20 ; i++)
{
List<MultipleChoiceSingleCorrect> multipleChoiceSingleCorrects = new MultipleChoiceSingleCorrectServicesImpl().getItemDetailsByItemID(i);
for (MultipleChoiceSingleCorrect multipleChoiceSingleCorrect : multipleChoiceSingleCorrects) {
Paragraph paragraph2 =new Paragraph();
paragraph2.setKeepTogether(true);
paragraph2.add(multipleChoiceSingleCorrect.getItemText());
paragraph2.add(Chunk.NEWLINE);
RomanList oplist = new RomanList();
oplist.setIndentationLeft(20);
for (OptionSingleCorrect optionSingleCorrect : multipleChoiceSingleCorrect.getOptionList()) {
oplist.add(optionSingleCorrect.getOptionText());
}
paragraph2.add(oplist);
paragraph2.setSpacingBefore(20);
ListItem listItem =new ListItem();
listItem.setKeepTogether(true);
listItem.add(paragraph2);
list.add(listItem);
}
}
document.add(list);
document.close();
response.setContentLength(OutputStream.size());
response.setContentType("application/pdf");
response.setHeader("Content-disposition", "attachment; filename=" + Filename);
ServletOutputStream out = response.getOutputStream();
OutputStream.writeTo(out);
out.flush();
}
catch (Exception e)
{
e.printStackTrace();
}