Add an image to an XWPFDocument using Apache POI - java

I have tried adding an image to the header of an XWPFDocument with no success. I am using Apache POI.
Here is what I am currently using as a solution:
Header creation
XWPFDocument document = new XWPFDocument(OPCPackage.open(docxInputStream));
CTP headerCtp = CTP.Factory.newInstance();
CTR headerCtr = headerCtp.addNewR();
XWPFParagraph headerParagraph = new XWPFParagraph(headerCtp, document);
XWPFRun run = headerParagraph.getRun(headerCtr);
InputStream pictureInputStream = new FileInputStream("D:\\logo.jpg");
run.addPicture(pictureInputStream, XWPFDocument.PICTURE_TYPE_JPEG, "logo.jpg", 300, 150);
pictureInputStream.close();
run.addTab();
run.setText(contentName);
setTabStop(headerCtp, STTabJc.Enum.forString("right"), BigInteger.valueOf(9000));
XWPFParagraph[] headerParagraphs = {headerParagraph};
CTSectPr sectPr = document.getDocument().getBody().addNewSectPr();
XWPFHeaderFooterPolicy headerFooterPolicy = new XWPFHeaderFooterPolicy(document, sectPr);
headerFooterPolicy.createHeader(STHdrFtr.DEFAULT, headerParagraphs);
setTabStop method
private static void setTabStop(CTP oCTP, STTabJc.Enum oSTTabJc, BigInteger oPos) {
CTPPr oPPr = oCTP.getPPr();
if (oPPr == null) {
oPPr = oCTP.addNewPPr();
}
CTTabs oTabs = oPPr.getTabs();
if (oTabs == null) {
oTabs = oPPr.addNewTabs();
}
CTTabStop oTabStop = oTabs.addNewTab();
oTabStop.setVal(oSTTabJc);
oTabStop.setPos(oPos);
}
The trouble I am having is that the image is loaded in the run, meaning the size of the pictures array is 1, however it isn't getting displayed in the document.
I have tried numerous solutions such as the following ones:
Add image into a word .docx document header using Apache POI XWPF
how to add a picture to a .docx document with Apache POI XWPF in java
Java - POI - Add a picture to the header
How i can add an Image as my header in a word document using Apache POI
Any hints and ideas as to what I may be doing wrong are welcome.
Thanks.

Related

Java Apache POI: place an image in a specific location

I need to place an image in a specific location in docx file. I can place an image at any paragraph and even create a new paragraph, but aligning breaks.
I tried to put a placeholder in the document and put my image there. Here is my code:
try (XWPFDocument doc = new XWPFDocument(
Objects.requireNonNull(getClass().getClassLoader().getResourceAsStream(filePath)));
) {
List<XWPFParagraph> xwpfParagraphList = doc.getParagraphs();
for (XWPFParagraph xwpfParagraph : xwpfParagraphList) {
if (Objects.equals(xwpfParagraph.getText().trim(), "QR")) {
InputStream is = new ByteArrayInputStream(qr);
XWPFRun qrRun = xwpfParagraph.createRun();
qrRun.addPicture(is, XWPFDocument.PICTURE_TYPE_JPEG, "qr", Units.toEMU(100), Units.toEMU(120));
is.close();
}
...
and the output docx looks like this:
enter image description here
How to place an image at the place, where the QR placeholder is located?

Generate Inter-Document Hyperlink with Apache POI in Java

I'm generating an XWPFDocument with Apache POI (never used it before this) and I'd like to link one paragraph to another paragraph inside the same .docx document. Is this possible using POI's native functionality or do I need to deep-dive into XML Bean wrapper classes (i.e. CTP) to hand-jam this or am I out of luck? Every instance of a question regarding hyperlinks and POI that I have seen references creating either an external-type hyperlink or a link between Excel workbook sheets. I am as of now only able to generate a 'hyperlink' in the sense of ctrl-clicking the paragraph inside the finished document and it appears to simply do a text search starting from the top of the document. Here's the code I am currently using to achieve this. Thanks in advance!
public static void addInternalHyperlink(XWPFParagraph origin, String text, XWPFParagraph target) {
if (target != null) {
// Create the hyperlink itself
CTHyperlink link = origin.getCTP().addNewHyperlink();
link.setAnchor(target.getText());
// Create hyperlink text
CTText linkText = CTText.Factory.newInstance();
linkText.setStringValue(text);
CTR ctr = CTR.Factory.newInstance();
ctr.setTArray(new CTText[] {linkText});
// Format hyperlink text
CTFonts fonts = CTFonts.Factory.newInstance();
fonts.setAscii("Times New Roman");
CTRPr rpr = ctr.addNewRPr();
CTColor color = CTColor.Factory.newInstance();
color.setVal("0000FF");
rpr.setColor(color);
CTRPr rpr1 = ctr.addNewRPr();
rpr1.addNewU().setVal(STUnderline.SINGLE);
// Insert formatted text into link
link.setRArray(new CTR[] {ctr});
}
}
Please note that I'd like to use the 'origin' argument as the paragraph containing the actual link, the 'text' argument as the link text, and the 'target' argument as the actual link destination.
UPDATE: Here's an XML snippet containing a sample paragraph which I have linked to a section heading via the Word GUI.
<w:p w14:paraId="5B1C3A0C" w14:textId="659E388D" w:rsidR="00A4419C" w:rsidRDefault="00A4419C" w:rsidP="00A4419C"><w:hyperlink w:anchor="_Another_Heading" w:history="1"><w:r w:rsidRPr="00A4419C"><w:rPr><w:rStyle w:val="Hyperlink"/></w:rPr><w:t>Here is some stuff that could b</w:t></w:r><w:r w:rsidRPr="00A4419C"><w:rPr><w:rStyle w:val="Hyperlink"/></w:rPr><w:t>e</w:t></w:r><w:r w:rsidRPr="00A4419C"><w:rPr><w:rStyle w:val="Hyperlink"/></w:rPr><w:t xml:space="preserve"> the link</w:t></w:r></w:hyperlink></w:p><w:p w14:paraId="19996B78" w14:textId="5C39B081" w:rsidR="00A4419C" w:rsidRPr="00A4419C" w:rsidRDefault="00A4419C" w:rsidP="00A4419C"><w:pPr><w:pStyle w:val="Heading1"/></w:pPr><w:bookmarkStart w:id="0" w:name="_Another_Heading"/><w:bookmarkEnd w:id="0"/><w:r><w:t>Another Heading</w:t></w:r><w:bookmarkStart w:id="1" w:name="_GoBack"/><w:bookmarkEnd w:id="1"/></w:p>
The solution falls into two parts.
First we need a XWPFHyperlinkRun whose target is an anchor in the document.
Second we need that target anchor, which can be a bookmark in the document for example. So we need creating such bookmark in the document.
Unfortunately both is not supported using only high level classes of apache poi until now. So we need the low level classes form ooxml-schemas too.
The following code works using apache poi 4.0.0 together with ooxml-schemas-1.4.
import java.io.FileOutputStream;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTBookmark;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTHyperlink;
import java.math.BigInteger;
public class CreateWordHyperlinkBookmark {
static XWPFHyperlinkRun createHyperlinkRunToAnchor(XWPFParagraph paragraph, String anchor) throws Exception {
CTHyperlink cthyperLink=paragraph.getCTP().addNewHyperlink();
cthyperLink.setAnchor(anchor);
cthyperLink.addNewR();
return new XWPFHyperlinkRun(
cthyperLink,
cthyperLink.getRArray(0),
paragraph
);
}
static XWPFParagraph createBookmarkedParagraph(XWPFDocument document, String anchor, int bookmarkId) {
XWPFParagraph paragraph = document.createParagraph();
CTBookmark bookmark = paragraph.getCTP().addNewBookmarkStart();
bookmark.setName(anchor);
bookmark.setId(BigInteger.valueOf(bookmarkId));
XWPFRun run = paragraph.createRun();
paragraph.getCTP().addNewBookmarkEnd().setId(BigInteger.valueOf(bookmarkId));
return paragraph;
}
public static void main(String[] args) throws Exception {
XWPFDocument document = new XWPFDocument();
String anchor = "hyperlink_target";
int bookmarkId = 0;
XWPFParagraph paragraph = document.createParagraph();
XWPFRun run = paragraph.createRun();
run.setText("This is a text paragraph having ");
//create hyperlink run
XWPFHyperlinkRun hyperlinkrun = createHyperlinkRunToAnchor(paragraph, anchor);
hyperlinkrun.setText("a link to an bookmark anchor");
hyperlinkrun.setColor("0000FF");
hyperlinkrun.setUnderline(UnderlinePatterns.SINGLE);
run = paragraph.createRun();
run.setText(" in it.");
//some empty paragraphs
for (int i = 0; i < 10; i++) {
paragraph = document.createParagraph();
}
//create bookmarked paragraph as the hyperlink target
paragraph = createBookmarkedParagraph(document, anchor, bookmarkId++);
run = paragraph.getRuns().get(0);
run.setText("This is the target.");
FileOutputStream out = new FileOutputStream("CreateWordHyperlinkBookmark.docx");
document.write(out);
out.close();
document.close();
}
}

insert header(left, center & right) in ms word using apache poi 3.11

I need to insert header like the screenshot below in word document using apache poi
I have a code to insert the header. But it aligned to left like the screenshot below:
I used below code to insert header:
// write header content
XWPFDocument docx = new XWPFDocument();
CTSectPr sectPr = docx.getDocument().getBody().addNewSectPr();
XWPFHeaderFooterPolicy policy = new XWPFHeaderFooterPolicy(docx,sectPr);
CTP ctpHeader = CTP.Factory.newInstance();
CTR ctrHeader = ctpHeader.addNewR();
CTText ctHeader = ctrHeader.addNewT();
String headerText = "This is header";
ctHeader.setStringValue(headerText);
XWPFParagraph headerParagraph = new XWPFParagraph(ctpHeader, docx);
XWPFParagraph[] parsHeader = new XWPFParagraph[1];
parsHeader[0] = headerParagraph;
policy.createHeader(XWPFHeaderFooterPolicy.DEFAULT, parsHeader);
FileOutputStream out = new FileOutputStream("D:/giri.docx");
docx.write(out);
out.close();
System.out.println("Done");
XWPFHeader header=policy.getDefaultHeader();
CTP ctpHeader = CTP.Factory.newInstance();
CTR ctrHeader = ctpHeader.addNewR();
CTText ctheader = ctrHeader.addNewT();
String HeaderText = "TSS Word Documentsss";
//ctheader.set(HeaderText);
XWPFParagraph headerParagraph = new XWPFParagraph(ctpHeader, document);
XWPFRun headerRun= headerParagraph.createRun();
headerRun.setBold(true);
headerRun.setFontSize(39);
headerRun.setColor("808000");
headerRun.setImprinted(true);
headerRun.setShadow(true);
headerRun.setCapitalized(true);
headerRun.setUnderline(UnderlinePatterns.DOT_DOT_DASH);
headerRun.setText(HeaderText);
headerParagraph.setAlignment(ParagraphAlignment.CENTER);
headerParagraph.setBorderBottom(Borders.BASIC_BLACK_DASHES);
XWPFParagraph[] parsHeader = new XWPFParagraph[1];
parsHeader[0] = headerParagraph;
policy.createHeader(XWPFHeaderFooterPolicy.DEFAULT, parsHeader);
Unlike Excel, Word doesn't have left, centre and right headers - Word has a header. If you want three separate entries on a single line, you can format a paragraph with the appropriate alignment (e.g. centred/justified) and tab-stops (possibly 3 centred, or one each of left, centre and right), then insert tab characters into the text you're inserting. Alternatively, for multi-line inputs especially, you could insert a 3-column table with the appropriate cell formatting and send the outputs to the relevant cells.
In VBA, you might add a table to the page header using code like:
With ActiveDocument
.Tables.Add Range:=.Sections.First.Headers(wdHeaderFooterPrimary).Range, NumRows:=1, NumColumns:=3, AutoFitBehavior:=wdAutoFitFixed
End With
I'll leave it to you to do the C# conversion.

Apache poi replace existing picture on header

Is there any way to replace an image on word(docx) file header by name of the image with apache poi? I'am thinking about that:
+--------------------------------+
+HEADER myimage.jpeg-+
+ -----------BODY------------+
+--------------------------------+
replaceImage("myimage.jpeg", newPictureInputStream,
"newPicture_name.jpeg");
Here what I tried:
XWPFParagraph originalParagraph = null;
originalParagraph = getPictureParagraphInHead(lookingPictureName);
ListIterator<XWPFRun> it = originalParagraph.getRuns().listIterator();
XWPFRun replacedRun = null;
while (it.hasNext()) {
XWPFRun run = it.next();
int runIDX = it.nextIndex();
if (run.getEmbeddedPictures().size() > 0) {
XWPFRun newRun = null;
newRun = new XWPFRun(run.getCTR(), (IRunBody) originalParagraph);
originalParagraph.addRun(newRun);
originalParagraph.removeRun(originalParagraph.getRuns().indexOf(run));
break;
}
}
I'm not sure if you can get the "filename" of the image with POI. It's probably in the XML so you might have to make your own method for finding the image.
To get the Header you do:
XWPFHeaderFooterPolicy policy = new XWPFHeaderFooterPolicy(doc); // XWPFDocument
XWPFHeader header = policy.getDefaultHeader();
And to delete the images, get the XWPFRun from your paragraph (cell/row/table..)
CTR ctr = myRun.getCTR(); //
List<CTDrawing> images = ctr.getDrawingList();
for (int i=0; i<images.size(); i++)
{
ctr.removeDrawing(i);
}

Insert .pdf doc or .png image content into a .docx file using java

How can I insert pdf or png content into a docx file using java?
I've tried using Apache POI API in the following way, but it is not working (it generates some junk doc file):
XWPFDocument doc = new XWPFDocument();
String pdf = "D://capture1.pdf";
PdfReader reader = new PdfReader(pdf);
PdfReaderContentParser parser = new PdfReaderContentParser(reader);
for (int i = 1; i <= reader.getNumberOfPages(); i++) {
TextExtractionStrategy strategy = parser.processContent(i,new SimpleTextExtractionStrategy());
String text = strategy.getResultantText();
XWPFParagraph p = doc.createParagraph();
XWPFRun run = p.createRun();
run.setText(text);
run.addBreak(BreakType.PAGE);
}
FileOutputStream out1 = new FileOutputStream("D://javadomain1.docx");
doc.write(out1);
out1.close();
reader.close();
System.out.println("Document converted successfully");
You should be able to do it with POI, and you can certainly do it using docx4j.
Here's sample code for inserting an image using docx4j.
Note that to "insert a PDF", you need to OLE embed it. That's more difficult, since you need to convert the PDF to a suitable binary OLE object. In docx4j, helper code for doing this is part of the commercial Enterprise edition.

Categories