前面我们介绍了如何使用Spire.Doc for Java 为Word文档添加文本水印和图片水印。当Word 文档中的某些部分,如段落,文本域Text Range, 表格,文本框和图形设置了背景色时,会出现水印被遮挡现象。该示例将详细介绍在Java应用程序中,给Word文档添加图片水印时移除段落,文本域,表格和文本框的背景色。
import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.*;
import java.awt.*;
public class WordWatermark {
public static void main(String[] args) {
//加载文档
Document document = new Document("Sample.docx");
//移除背景色
SetNoFillForParagraphsAndTablesAndTextBoxes(document);
//插入图片水印
insertImageWatermark(document);
//保存文档
String output = "Result.docx";
document.saveToFile(output, FileFormat.Docx);
}
public static void insertImageWatermark(Document document) {
PictureWatermark picture = new PictureWatermark();
picture.setPicture("logo.jpg");
picture.setScaling(250);
picture.isWashout(false);
document.setWatermark(picture);
}
static void SetNoFillForParagraphsAndTablesAndTextBoxes(Document document) {
Section section;
Paragraph paragraph;
TextRange textRange;
for (int i = 0; i < document.getSections().getCount(); i++) {
section = document.getSections().get(i);
//移除段落中的背景色
for (int j = 0; j < section.getBody().getParagraphs().getCount(); j++) {
paragraph = section.getBody().getParagraphs().get(j);
RemoveBackgroudColorOfParagraph(paragraph);
}
Table table;
//移除表格中的背景色
for (int t = 0; t < section.getBody().getTables().getCount(); t++) {
table = section.getBody().getTables().get(t);
table.getTableFormat().clearBackground();
for(int r=0;r<table.getRows().getCount();r++){
TableRow row =table.getRows().get(r);
row.getRowFormat().clearBackground();
for(int c=0;c<row.getCells().getCount();c++){
TableCell cell = row.getCells().get(c);
cell.getCellFormat().clearBackground();
for(int p=0;p<cell.getParagraphs().getCount();p++) {
paragraph = (Paragraph) cell.getParagraphs().get(p);
//移除段落中的背景色
RemoveBackgroudColorOfParagraph(paragraph);
}
}
}
}
//移除文本框中的背景色
TextBox textBox;
for (int n = 0; n < document.getTextBoxes().getCount(); n++) {
document.getTextBoxes().get(n).getFormat().setFillColor(null);
for(int t=0;t<document.getTextBoxes().getCount();t++) {
textBox = document.getTextBoxes().get(t);
for(int p=0;p<textBox.getChildObjects().getCount();p++)
if(textBox.getChildObjects().get(p) instanceof Paragraph) {
paragraph = (Paragraph) textBox.getChildObjects().get(p);
//移除段落中的背景色
RemoveBackgroudColorOfParagraph(paragraph);
}
}
}
}
}
static void RemoveBackgroudColorOfParagraph(Paragraph paragraph)
{
TextRange textRange;
paragraph.getFormat().setBackColor(new Color(0, 0, 0, 0));
for (int k = 0; k < paragraph.getChildObjects().getCount(); k++) {
if (paragraph.getChildObjects().get(k) instanceof TextRange) {
textRange = (TextRange) paragraph.getChildObjects().get(k);
//移除文本域中的背景色
textRange.getCharacterFormat().setTextBackgroundColor(new Color(0, 0, 0, 0));
}
}
}
}
效果图: