向Docx4j生成的word文档添加图片和布局--第一部分


添加图


本示例我们向新创建的word文档添加一张嵌入式图片。这并非很难,因为Docx4j示例包含了几种做这件事的方法。但是有几个问题我不是特别地清楚,所以我稍微重构了那个例子改为只添加一个内联图片并且添加了一些注释来解释发生了什么。


[java] view plaincopy

1.  public class AddingAnInlineImage {  

2.      /** 

3.       *  像往常一样, 我们创建了一个包(package)来容纳文档. 

4.       *  然后我们创建了一个指向将要添加到文档的图片的文件对象.为了能够对图片做一些操作, 我们将它转换 

5.       *  为字节数组. 最后我们将图片添加到包中并保存这个包(package). 

6.       */  

7.      public static void main (String[] args) throws Exception {  

8.          WordprocessingMLPackage  wordMLPackage = WordprocessingMLPackage.createPackage();  

9.     

10.         File file = new File("src/main/resources/iProfsLogo.png");  

11.         byte[] bytes = convertImageToByteArray(file);  

12.         addImageToPackage(wordMLPackage, bytes);  

13.    

14.         wordMLPackage.save(new java.io.File("src/main/files/HelloWord7.docx"));  

15.     }  

16.    

17.     /** 

18.      *  Docx4j拥有一个由字节数组创建图片部件的工具方法, 随后将其添加到给定的包中. 为了能将图片添加 

19.      *  到一个段落中, 我们需要将图片转换成内联对象. 这也有一个方法, 方法需要文件名提示, 替换文本,  

20.      *  两个id标识符和一个是嵌入还是链接到的指示作为参数. 

21.      *  一个id用于文档中绘图对象不可见的属性, 另一个id用于图片本身不可见的绘制属性. 最后我们将内联 

22.      *  对象添加到段落中并将段落添加到包的主文档部件. 

23.      * 

24.      *  @param wordMLPackage 要添加图片的包 

25.      *  @param bytes         图片对应的字节数组 

26.      *  @throws Exception    不幸的createImageInline方法抛出一个异常(没有更多具体的异常类型) 

27.      */  

28.     private static void addImageToPackage(WordprocessingMLPackage wordMLPackage,  

29.                             byte[] bytes) throws Exception {  

30.         BinaryPartAbstractImage imagePart = BinaryPartAbstractImage.createImagePart(wordMLPackage, bytes);  

31.    

32.         int docPrId = 1;  

33.         int cNvPrId = 2;  

34.         Inline inline = imagePart.createImageInline("Filename hint","Alternative text", docPrId, cNvPrId, false);  

35.    

36.         P paragraph = addInlineImageToParagraph(inline);  

37.    

38.         wordMLPackage.getMainDocumentPart().addObject(paragraph);  

39.     }  

40.    

41.     /** 

42.      *  创建一个对象工厂并用它创建一个段落和一个可运行块R. 

43.      *  然后将可运行块添加到段落中. 接下来创建一个图画并将其添加到可运行块R中. 最后我们将内联 

44.      *  对象添加到图画中并返回段落对象. 

45.      * 

46.      * @param   inline 包含图片的内联对象. 

47.      * @return  包含图片的段落 

48.      */  

49.     private static P addInlineImageToParagraph(Inline inline) {  

50.         // 添加内联对象到一个段落中  

51.         ObjectFactory factory = new ObjectFactory();  

52.         P paragraph = factory.createP();  

53.         R run = factory.createR();  

54.         paragraph.getContent().add(run);  

55.         Drawing drawing = factory.createDrawing();  

56.         run.getContent().add(drawing);  

57.         drawing.getAnchorOrInline().add(inline);  

58.         return paragraph;  

59.     }  

60.    

61.     /** 

62.      * 将图片从文件对象转换成字节数组. 

63.      *  

64.      * @param file  将要转换的文件 

65.      * @return      包含图片字节数据的字节数组 

66.      * @throws FileNotFoundException 

67.      * @throws IOException 

68.      */  

69.     private static byte[] convertImageToByteArray(File file)  

70.             throws FileNotFoundException, IOException {  

71.         InputStream is = new FileInputStream(file );  

72.         long length = file.length();  

73.         // 不能使用long类型创建数组, 需要用int类型.  

74.         if (length > Integer.MAX_VALUE) {  

75.             System.out.println("File too large!!");  

76.         }  

77.         byte[] bytes = new byte[(int)length];  

78.         int offset = 0;  

79.         int numRead = 0;  

80.         while (offset < bytes.length && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {  

81.             offset += numRead;  

82.         }  

83.         // 确认所有的字节都没读取  

84.         if (offset < bytes.length) {  

85.             System.out.println("Could not completely read file " +file.getName());  

86.         }  

87.         is.close();  

88.         return bytes;  

89.     }  

90. }  


在表格中添加图


现在我们知道了如何在文档中添加图片,如果在我们前面博客中的表格中添加图片将会使表格更漂亮。正如你将在下面看到的代码一样,并不比我们前面例子中所做的困难很多。

[java] view plaincopy

1.  public class AddingAnInlineImageToTable {  

2.      private static WordprocessingMLPackage  wordMLPackage;  

3.      private static ObjectFactory factory;  

4.     

5.      /** 

6.       *  首先我们创建包和对象工厂, 因此在类的随处我们都可以使用它们. 然后我们创建一个表格并添加 

7.       *  边框. 接下来我们创建一个表格行并在第一个域添加一些文本. 

8.       *  对于第二个域, 我们用与前面一样的图片创建一个段落并添加进去. 最后把行添加到表格中, 并将 

9.       *  表格添加到包中, 然后保存这个包. 

10.      */  

11.     public static void main (String[] args) throws Exception {  

12.         wordMLPackage = WordprocessingMLPackage.createPackage();  

13.         factory = Context.getWmlObjectFactory();  

14.    

15.         Tbl table = factory.createTbl();  

16.         addBorders(table);  

17.    

18.         Tr tr = factory.createTr();  

19.    

20.         P paragraphOfText = wordMLPackage.getMainDocumentPart().createParagraphOfText("Field 1");  

21.         addTableCell(tr, paragraphOfText);  

22.    

23.         File file = new File("src/main/resources/iProfsLogo.png");  

24.         P paragraphWithImage = addInlineImageToParagraph(createInlineImage(file));  

25.         addTableCell(tr, paragraphWithImage);  

26.    

27.         table.getContent().add(tr);  

28.    

29.         wordMLPackage.getMainDocumentPart().addObject(table);  

30.         wordMLPackage.save(new java.io.File("src/main/files/HelloWord8.docx"));  

31.     }  

32.    

33.     /** 

34.      * 用给定的段落作为内容向给定的行中添加一个单元格. 

35.      * 

36.      * @param tr 

37.      * @param paragraph 

38.      */  

39.     private static void addTableCell(Tr tr, P paragraph) {  

40.         Tc tc1 = factory.createTc();  

41.         tc1.getContent().add(paragraph);  

42.         tr.getContent().add(tc1);  

43.     }  

44.    

45.     /** 

46.      *  向新的段落中添加内联图片并返回这个段落. 

47.      *  这个方法与前面例子中的方法没有区别. 

48.      * 

49.      * @param inline 

50.      * @return 

51.      */  

52.     private static P addInlineImageToParagraph(Inline inline) {  

53.         // Now add the in-line image to a paragraph  

54.         ObjectFactory factory = new ObjectFactory();  

55.         P paragraph = factory.createP();  

56.         R run = factory.createR();  

57.         paragraph.getContent().add(run);  

58.         Drawing drawing = factory.createDrawing();  

59.         run.getContent().add(drawing);  

60.         drawing.getAnchorOrInline().add(inline);  

61.         return paragraph;  

62.     }  

63.    

64.     /** 

65.      * 使用给定的文件创建一个内联图片. 

66.      * 跟前面例子中一样, 我们将文件转换成字节数组, 并用它创建一个内联图片. 

67.      * 

68.      * @param file 

69.      * @return 

70.      * @throws Exception 

71.      */  

72.     private static Inline createInlineImage(File file) throws Exception {  

73.         byte[] bytes = convertImageToByteArray(file);  

74.    

75.         BinaryPartAbstractImage imagePart = BinaryPartAbstractImage.createImagePart(wordMLPackage, bytes);  

76.    

77.         int docPrId = 1;  

78.         int cNvPrId = 2;  

79.    

80.         return imagePart.createImageInline("Filename hint", "Alternative text", docPrId, cNvPrId, false);  

81.     }  

82.    

83.     /** 

84.      * 将图片从文件转换成字节数组. 

85.      * 

86.      * @param file 

87.      * @return 

88.      * @throws FileNotFoundException 

89.      * @throws IOException 

90.      */  

91.     private static byte[] convertImageToByteArray(File file) throws FileNotFoundException, IOException {  

92.         InputStream is = new FileInputStream(file );  

93.         long length = file.length();  

94.         // You cannot create an array using a long, it needs to be an int.  

95.         if (length > Integer.MAX_VALUE) {  

96.             System.out.println("File too large!!");  

97.         }  

98.         byte[] bytes = new byte[(int)length];  

99.         int offset = 0;  

100.                 int numRead = 0;  

101.                 while (offset < bytes.length && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {  

102.                     offset += numRead;  

103.                 }  

104.                 // Ensure all the bytes have been read  

105.                 if (offset < bytes.length) {  

106.                     System.out.println("Could not completely read file "+file.getName());  

107.                 }  

108.                 is.close();  

109.                 return bytes;  

110.             }  

111.            

112.             /** 

113.              * 给表格添加简单的黑色边框. 

114.              * 

115.              * @param table 

116.              */  

117.             private static void addBorders(Tbl table) {  

118.                 table.setTblPr(new TblPr());  

119.                 CTBorder border = new CTBorder();  

120.                 border.setColor("auto");  

121.                 border.setSz(new BigInteger("4"));  

122.                 border.setSpace(new BigInteger("0"));  

123.                 border.setVal(STBorder.SINGLE);  

124.            

125.                 TblBorders borders = new TblBorders();  

126.                 borders.setBottom(border);  

127.                 borders.setLeft(border);  

128.                 borders.setRight(border);  

129.                 borders.setTop(border);  

130.                 borders.setInsideH(border);  

131.                 borders.setInsideV(border);  

132.                 table.getTblPr().setTblBorders(borders);  

133.             }  

134.         }  


添加换页


添加换页符相当地简单。Docx4j拥有一个叫作Br的break对象,这个对象有一个type属性,这种情况下我们需要将其设置为page,type其它可选的值为column和textWrapping。这个break可以很简单地添加到段落中。


[java] view plaincopy

1.  public class AddingAPageBreak {  

2.      private static ObjectFactory factory;  

3.      private static WordprocessingMLPackage  wordMLPackage;  

4.     

5.      public static void main (String[] args) throws Docx4JException {  

6.          wordMLPackage = WordprocessingMLPackage.createPackage();  

7.          factory = Context.getWmlObjectFactory();  

8.     

9.          wordMLPackage.getMainDocumentPart().addParagraphOfText("Hello Word!");  

10.    

11.         addPageBreak();  

12.    

13.         wordMLPackage.getMainDocumentPart().addParagraphOfText("This is page 2!");  

14.         wordMLPackage.save(new java.io.File("src/main/files/HelloWord11.docx") );  

15.     }  

16.    

17.     /** 

18.      * 向文档添加一个换行符 

19.      */  

20.     private static void addPageBreak() {  

21.         MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();  

22.    

23.         Br breakObj = new Br();  

24.         breakObj.setType(STBrType.PAGE);  

25.    

26.         P paragraph = factory.createP();  

27.         paragraph.getContent().add(breakObj);  

28.         documentPart.getJaxbElement().getBody().getContent().add(paragraph);  

29.     }  

30. }  


添加目录


添加目录十分地简单。在Word中这是一个可以被添加的域,在Docx4j中是一样的。仅有一个你需要知道的小问题,就是像这样创建的一个文档,在你第一次打开它的时候,Word会给你一个此文档可能包含指向其它文件的域的提示信息,询问你是否要更新这些域。如果你点击了yes回应询问,Word将会将目录表域转换为真正的目录。如果你点击了no,你会看到这个文档没有目录。


[java] view plaincopy

1.  public class AddingTableOfContent {  

2.      private static ObjectFactory factory;  

3.     

4.      /** 

5.       *  首先我们创建对象工厂和包并从包中抽出文档部件. 然后我们添加目录表, 后面跟着一些带有分类 

6.       *  标题样式的段落. 最后我们保存包. 

7.       */  

8.      public static void main(String[] args) throws Docx4JException {  

9.          factory = Context.getWmlObjectFactory();  

10.         WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.createPackage();  

11.         MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();  

12.    

13.         addTableOfContent(documentPart);  

14.    

15.         documentPart.addStyledParagraphOfText("Heading1", "Hello 1");  

16.         documentPart.addStyledParagraphOfText("Heading2", "Hello 2");  

17.         documentPart.addStyledParagraphOfText("Heading3", "Hello 3");  

18.         documentPart.addStyledParagraphOfText("Heading1", "Hello 1");  

19.    

20.         wordMLPackage.save(new File("src/main/files/HelloWord10.docx"));  

21.     }  

22.    

23.     /** 

24.      *  将目录表添加到文档. 

25.      *   

26.      *  首先我们创建段落. 然后添加标记域开始的指示符, 然后添加域内容(真正的目录表), 接着添加域 

27.      *  结束的指示符. 最后将段落添加到给定文档的JAXB元素中. 

28.      * 

29.      *  @param documentPart 

30.      */  

31.     private static void addTableOfContent(MainDocumentPart documentPart) {  

32.         P paragraph = factory.createP();  

33.    

34.         addFieldBegin(paragraph);  

35.         addTableOfContentField(paragraph);  

36.         addFieldEnd(paragraph);  

37.    

38.         documentPart.getJaxbElement().getBody().getContent().add(paragraph);  

39.     }  

40.    

41.     /** 

42.      * (不知道该怎么翻译, 因此将英文原注释保留) 

43.      *  Adds the field that Word uses to create a table of content to the paragraph. 

44.      * 

45.      *  First we create a run and a text. Then we indicate that all spaces in the 

46.      *  text are to be preserved and set the value to that of the TOC field. 

47.      *  This field definition takes some arguments. The exact definition can be 

48.      *  found in §17.16.5.58 of the Office Open XML standard. In this case we 

49.      *  specify that we want to include all paragrapsh formatted with headings of 

50.      *  levels 1-3 (\0 “1-3”). We also specify that we want all entries to be 

51.      *  hyperlinks (\h), that we want to hide tab leader and page numbers in Web 

52.      *  layout view (\z), and that we want to use the applied paragraph outline 

53.      *  level (\u). 

54.      *  Finally we take the text and use it to create a JAXB element containing text 

55.      *  and add this to the run, which we then add to the given paragraph. 

56.      *   

57.      *  将Word用于创建目录表的域添加到段落中. 

58.      *   

59.      *  首先创建一个可运行块和一个文本. 然后指出文本中所有的空格都被保护并给TOC域设置值. 这个域定义 

60.      *  需要一些参数, 确切定义可以在Office Open XML标准的§17.16.5.58找到, 这种情况我们指定所有 

61.      *  段落使用1-3级别的标题来格式化(\0 "1-3"). 我们同时指定所有的实体作为超链接(\h), 而且在Web 

62.      *  视图中隐藏标签和页码(\z), 我们要使用段落大纲级别应用(\u). 

63.      *  最后使用文本对象创建了一个JAXB元素包含文本并添加到随后被添加到段落中的可运行块中.  

64.      *   

65.      *  @param paragraph 

66.      */  

67.     private static void addTableOfContentField(P paragraph) {  

68.         R run = factory.createR();  

69.         Text txt = new Text();  

70.         txt.setSpace("preserve");  

71.         txt.setValue("TOC \\o \"1-3\" \\h \\z \\u");  

72.         run.getContent().add(factory.createRInstrText(txt));  

73.         paragraph.getContent().add(run);  

74.     }  

75.    

76.     /** 

77.      *  每个域都需要用复杂的域字符来确定界限. 本方法向给定段落添加在真正域之前的界定符. 

78.      *   

79.      *  再一次以创建一个可运行块开始, 然后创建一个域字符来标记域的起始并标记域是'脏的'因为我们想要 

80.      *  在整个文档生成之后进行内容更新. 

81.      *  最后将域字符转换成JAXB元素并将其添加到可运行块, 然后将可运行块添加到段落中. 

82.      * 

83.      *  @param paragraph 

84.      */  

85.     private static void addFieldBegin(P paragraph) {  

86.         R run = factory.createR();  

87.         FldChar fldchar = factory.createFldChar();  

88.         fldchar.setFldCharType(STFldCharType.BEGIN);  

89.         fldchar.setDirty(true);  

90.         run.getContent().add(getWrappedFldChar(fldchar));  

91.         paragraph.getContent().add(run);  

92.     }  

93.    

94.     /** 

95.      *  每个域都需要用复杂的域字符来确定界限. 本方法向给定段落添加在真正域之后的界定符. 

96.      *   

97.      *  跟前面一样, 从创建可运行块开始, 然后创建域字符标记域的结束, 最后将域字符转换成JAXB元素并 

98.      *  将其添加到可运行块, 可运行块再添加到段落中. 

99.      * 

100.              *  @param paragraph 

101.              */  

102.             private static void addFieldEnd(P paragraph) {  

103.                 R run = factory.createR();  

104.                 FldChar fldcharend = factory.createFldChar();  

105.                 fldcharend.setFldCharType(STFldCharType.END);  

106.                 run.getContent().add(getWrappedFldChar(fldcharend));  

107.                 paragraph.getContent().add(run);  

108.             }  

109.            

110.             /** 

111.              *  创建包含给定复杂域字符的JAXBElement的便利方法. 

112.              * 

113.              *  @param fldchar 

114.              *  @return 

115.              */  

116.             public static JAXBElement getWrappedFldChar(FldChar fldchar) {  

117.                 return new JAXBElement(new QName(Namespaces.NS_WORD12, "fldChar"), FldChar.class, fldchar);  

118.             }  

119.         }  


你可能感兴趣的:(word,docx4j)