本文介绍如何使用Spire.Doc for Java添加可填充的窗体域,包括文本框、复选框、下拉列表框,到Word文档。
import com.spire.doc.*;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.documents.ParagraphStyle;
import com.spire.doc.documents.VerticalAlignment;
import com.spire.doc.fields.CheckBoxFormField;
import com.spire.doc.fields.DropDownFormField;
import com.spire.doc.fields.TextFormField;
public class CreateFormFields {
public static void main(String[] args) {
//创建Word文档,添加一个section
Document doc = new Document();
Section section = doc.addSection();
//添加一个表格
Table table = section.addTable();
table.resetCells(3,2);
//写入文本到指定单元格
Paragraph paragraph = table.getRows().get(0).getCells().get(0).addParagraph();
paragraph.appendText("文本框");
paragraph = table.getRows().get(1).getCells().get(0).addParagraph();
paragraph.appendText("复选框");
paragraph = table.getRows().get(2).getCells().get(0).addParagraph();
paragraph.appendText("下拉列表框");
//添加文本框到指定单元格
paragraph = table.getRows().get(0).getCells().get(1).addParagraph();
TextFormField textField = (TextFormField) paragraph.appendField("text", FieldType.Field_Form_Text_Input);
textField.setTextFieldType(TextFormFieldType.Regular_Text);
//添加复选框到指定单元格
paragraph = table.getRows().get(1).getCells().get(1).addParagraph();
CheckBoxFormField checkboxField = (CheckBoxFormField)paragraph.appendField("checkbox", FieldType.Field_Form_Check_Box);
//添加下拉列表框到指定单元格
paragraph = table.getRows().get(2).getCells().get(1).addParagraph();
DropDownFormField dropdownField = (DropDownFormField)paragraph.appendField("listbox",FieldType.Field_Form_Drop_Down);
dropdownField.getDropDownItems().add("英国");
dropdownField.getDropDownItems().add("美国");
dropdownField.getDropDownItems().add("其他");
//创建一个ParagraphStyle对象
ParagraphStyle style = new ParagraphStyle(doc);
style.setName("newFont");
style.getCharacterFormat().setFontName("宋体");
style.getCharacterFormat().setFontSize(13);
doc.getStyles().add(style);
for (int i = 0; i < table.getRows().getCount(); i++) {
//设置行高
table.getRows().get(i).setHeight(30f);
for (Object cell:table.getRows().get(i).getCells()){
if (cell instanceof TableCell)
{
//将每个单元格的垂直对齐方式设置为居中
((TableCell) cell).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle);
//应用段落样式到每个单元格的第一个段落
((TableCell) cell).getParagraphs().get(0).applyStyle(style.getName());
}
}
}
//保存文档
doc.saveToFile("output/AddFormFields.docx", FileFormat.Docx_2013);
}
}