Hi,
I want to insert a watermark in a Word file and convert it to PDF.
I’m using this code:
Document doc = new Document(“test.docx”);
insertWatermarkText(doc, “BORRADOR”);
doc.save(“test.pdf”);
public static void insertWatermarkText(Document doc, String watermarkText) throws Exception {
Shape watermark = new Shape(doc, ShapeType.TEXT_PLAIN_TEXT);
// Set up the text of the watermark.
watermark.getTextPath().setText(watermarkText);
watermark.getTextPath().setFontFamily(“Arial”);
watermark.setWidth(500);
watermark.setHeight(100);
// Text will be directed from the bottom-left to the top-right corner.
watermark.setRotation(-40);
// Remove the following two lines if you need a solid black text.
watermark.getFill().setColor(Color.GRAY); // Try LightGray to get more Word-style watermark
watermark.setStrokeColor(Color.GRAY); // Try LightGray to get more Word-style watermark
// Place the watermark in the page center.
watermark.setRelativeHorizontalPosition(RelativeHorizontalPosition.PAGE);
watermark.setRelativeVerticalPosition(RelativeVerticalPosition.PAGE);
watermark.setWrapType(WrapType.NONE);
watermark.setVerticalAlignment(VerticalAlignment.CENTER);
watermark.setHorizontalAlignment(HorizontalAlignment.CENTER);
// Create a new paragraph and append the watermark to this paragraph.
Paragraph watermarkPara = new Paragraph(doc);
watermarkPara.getParagraphBreakFont().setSize(0);
watermarkPara.appendChild(watermark);
// Insert the watermark into all headers of each document section.
for (Section sect : doc.getSections()) {
// There could be up to three different headers in each section, since we want
// the watermark to appear on all pages, insert into all headers.
insertWatermarkIntoHeader(watermarkPara, sect, HeaderFooterType.HEADER_PRIMARY);
insertWatermarkIntoHeader(watermarkPara, sect, HeaderFooterType.HEADER_FIRST);
insertWatermarkIntoHeader(watermarkPara, sect, HeaderFooterType.HEADER_EVEN);
}
}
private static void insertWatermarkIntoHeader(Paragraph watermarkPara, Section sect,
int headerType) throws Exception {
HeaderFooter header =
sect.getHeadersFooters().getByHeaderFooterType(headerType);
if (header == null) {
// There is no header of the specified type in the current section, create it.
header = new HeaderFooter(sect.getDocument(), headerType);
}
// Insert a clone of the watermark into the header.
header.appendChild(watermarkPara.deepClone(true));
sect.getHeadersFooters().add(header);
}
However, the watermark is inserting an space in the header (between the horizontal line and the text “Test Plantillas”). You can see it in the attached files.
Some zones of the Word document are protected, but if you need to unprotect them, the password is 1234.
Can you help me to avoid the watermark inserts this space?
Thank you very much.