Apache poi, Docx 文件 XWPFRun, XWPFParagraph

huangapple go评论47阅读模式
英文:

Apache poi, Docx file XWPFRun, XWPFParagraph

问题

如果有人有类似的示例或者有人可以做到,请帮我写一下

我无法将这两张图片放在Word文件的右侧和左侧。

Word文件已创建,但我无法更改其中图片的位置,并且在两张图片之间放置标题时出现了问题。

英文:

If anyone has a similar example or if someone can do it, please help me write it

I couldn't place the two images on the right and left sides of the word file.

The word file was created. but I could not change the position of the pictures in it and I had a problem placing the title between two pictures

答案1

得分: 1

我希望你真的不想伪造白宫管理和预算办公室的正式文件。

由于看起来标题部分位于Word文档的页眉中,放置两个标志的最简单方法是使用表格。在Word文档的页眉部分需要一个表格,该表格需要三列和一行。该行的左侧单元格左对齐,包含左侧标志。该行的右侧单元格右对齐,包含右侧标志。该行的中间单元格居中对齐,包含文本。

如何在Word文档的页眉部分创建表格已经得到了回答:https://stackoverflow.com/questions/39572996/how-to-add-a-table-to-header-or-footer/39578388#39578388

但是,当然,自此回答以来,Apache POI已经进一步开发。使用当前的Apache POI版本5.2.3,代码可能如下所示:

import java.io.FileOutputStream;
import java.io.FileInputStream;
import org.apache.poi.xwpf.usermodel.*;
import org.apache.poi.wp.usermodel.HeaderFooterType;
import org.apache.poi.util.Units;

import java.math.BigInteger;

public class CreateWordHeaderFooterTable {

 private static final int TWIPS_PER_INCH = 1440;

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

  try (XWPFDocument doc = new XWPFDocument();
        FileOutputStream out = new FileOutputStream("./CreateWordHeaderFooterTable.docx");
      ) {

   // 正文内容
   XWPFParagraph paragraph = doc.createParagraph();
   XWPFRun run = paragraph.createRun();
   run.setText("正文内容:");

   paragraph = doc.createParagraph();
   run = paragraph.createRun();
   run.setText("Lorem ipsum....");

   // 页眉内容
   // 创建页眉
   XWPFHeader header = doc.createHeader(HeaderFooterType.DEFAULT);

   // 在页眉中创建表格
   XWPFTable table = header.createTable(1, 3);
   // 表格占满宽度
   table.setWidth("100%");
   // 表格没有边框
   table.removeBorders();
   // 列宽度
   double[] dWidthsPCT = new double[]{20d, 60d, 20d};
   java.util.stream.Stream<String> stream =
    java.util.stream.DoubleStream.of(dWidthsPCT).boxed()
    .map(d -> String.valueOf(d) + "%");
   String[] widthsPCT = stream.toArray(String[]::new);
   /*
    * 为表格创建CTTblGrid,包含3列的宽度。
    * Libreoffice/Openoffice需要这个来接受列宽度。
    */
   // 只有列宽度的关系
   // 第一列
   table.getCTTbl().addNewTblGrid().addNewGridCol().setW(BigInteger.valueOf((int) (dWidthsPCT[0] / 100d * TWIPS_PER_INCH)));
   // 第二列
   table.getCTTbl().getTblGrid().addNewGridCol().setW(BigInteger.valueOf((int) (dWidthsPCT[1] / 100d * TWIPS_PER_INCH)));
   // 第三列
   table.getCTTbl().getTblGrid().addNewGridCol().setW(BigInteger.valueOf((int) (dWidthsPCT[2] / 100d * TWIPS_PER_INCH)));
   // 获取第一行
   XWPFTableRow row = table.getRow(0);
   if (row == null) row = table.createRow();
   // 设置列宽度
   XWPFTableCell cell;
   FileInputStream pictureIn;
   for (int i = 0; i < 3; i++) {
    cell = row.getCell(i);
    if (cell == null) cell = row.createCell();
    cell.setWidth(widthsPCT[i]);
   }
   // 设置单元格内容
   // 左侧单元格
   cell = row.getCell(0);
   if (cell.getParagraphs().size() > 0) {
    paragraph = cell.getParagraphs().get(0);
   } else {
    paragraph = cell.addParagraph();
   }
   paragraph.setAlignment(ParagraphAlignment.LEFT);
   run = paragraph.createRun();
   pictureIn = new FileInputStream("./leftLogo.png");
   run.addPicture(pictureIn, XWPFDocument.PICTURE_TYPE_PNG, "leftLogo.png", Units.toEMU(80), Units.toEMU(80));
   // 右侧单元格
   cell = row.getCell(2);
   if (cell.getParagraphs().size() > 0) {
    paragraph = cell.getParagraphs().get(0);
   } else {
    paragraph = cell.addParagraph();
   }
   paragraph.setAlignment(ParagraphAlignment.RIGHT);
   run = paragraph.createRun();
   pictureIn = new FileInputStream("./rightLogo.png");
   run.addPicture(pictureIn, XWPFDocument.PICTURE_TYPE_PNG, "rightLogo.png", Units.toEMU(80), Units.toEMU(80));
   // 中间单元格
   cell = row.getCell(1);
   if (cell.getParagraphs().size() > 0) {
    paragraph = cell.getParagraphs().get(0);
   } else {
    paragraph = cell.addParagraph();
   }
   paragraph.setAlignment(ParagraphAlignment.CENTER);
   run = paragraph.createRun();
   run.setText("LOREM IPSUM SEMIT DOLOR SIT AMET");
   run.addBreak();
   run.setText("consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata");

   // 页脚内容
   // 创建页脚
   XWPFFooter footer = doc.createFooter(HeaderFooterType.DEFAULT);
   paragraph = footer.getParagraphArray(0);
   if (paragraph == null) paragraph = footer.createParagraph();
   paragraph.setAlignment(ParagraphAlignment.CENTER);
   run = paragraph.createRun();
   run.setText("页脚内容:");

   // 写出文档
   doc.write(out);
  }
 }
}

请注意,这只是你提供的代码的翻译,不包括任何额外的信息或回答。

英文:

I hope you don't really want to fake official papers from The White House Office of Management and Budget.

As it looks like the header is in the header part of the Word document. And the simplest way to place the two logos as shown, is using a table. One would need a table in header part of the Word document. The table would need three columns and one row. The left cell in that row is left aligned and contains the left logo. The right cell in that row is right aligned and contains the right logo. The middle cell in that row is center aligned and contains the text.

How to create a table in header part of the Word document was answered already: https://stackoverflow.com/questions/39572996/how-to-add-a-table-to-header-or-footer/39578388#39578388

But, of course Apache POI was further developed since this answer. Using current Apache POI version 5.2.3, code could look like so:

<!-- language: java -->

import java.io.FileOutputStream;
import java.io.FileInputStream;
import org.apache.poi.xwpf.usermodel.*;
import org.apache.poi.wp.usermodel.HeaderFooterType;
import org.apache.poi.util.Units;
import java.math.BigInteger;
public class CreateWordHeaderFooterTable {
private static final int TWIPS_PER_INCH = 1440;
public static void main(String[] args) throws Exception {
try ( XWPFDocument doc = new XWPFDocument();
FileOutputStream out = new FileOutputStream(&quot;./CreateWordHeaderFooterTable.docx&quot;);
) {
// the body content
XWPFParagraph paragraph = doc.createParagraph();
XWPFRun run=paragraph.createRun();  
run.setText(&quot;The Body:&quot;);
paragraph = doc.createParagraph();
run=paragraph.createRun();  
run.setText(&quot;Lorem ipsum....&quot;);
// the header content
// create header start
XWPFHeader header = doc.createHeader(HeaderFooterType.DEFAULT);
// create table in header
XWPFTable table = header.createTable(1, 3);
// table spans full width
table.setWidth(&quot;100%&quot;);
// table has no borders
table.removeBorders();
// column widths
double[] dWidthsPCT = new double[]{20d, 60d, 20d};
java.util.stream.Stream&lt;String&gt; stream = 
java.util.stream.DoubleStream.of(dWidthsPCT).boxed()
.map(d -&gt; String.valueOf(d)+&quot;%&quot;);
String[] widthsPCT = stream.toArray(String[]::new);  
/*
* Create CTTblGrid for this table with widths of the 3 columns. 
* Necessary for Libreoffice/Openoffice to accept the column widths.
*/
// only relations of column widths
// f1rst col
table.getCTTbl().addNewTblGrid().addNewGridCol().setW(BigInteger.valueOf((int)(dWidthsPCT[0]/100d * TWIPS_PER_INCH)));
// second col
table.getCTTbl().getTblGrid().addNewGridCol().setW(BigInteger.valueOf((int)(dWidthsPCT[1]/100d * TWIPS_PER_INCH)));
// third col
table.getCTTbl().getTblGrid().addNewGridCol().setW(BigInteger.valueOf((int)(dWidthsPCT[2]/100d * TWIPS_PER_INCH)));
// get frist table row
XWPFTableRow row = table.getRow(0); if (row == null) row = table.createRow();
// set column widths
XWPFTableCell cell;
FileInputStream pictureIn;
for (int i = 0; i &lt; 3; i++) {
cell = row.getCell(i); if (cell == null) cell = row.createCell();
cell.setWidth(widthsPCT[i]);
}
// set cell contents
// left cell
cell = row.getCell(0);
if (cell.getParagraphs().size() &gt; 0) {
paragraph = cell.getParagraphs().get(0);
} else {
paragraph = cell.addParagraph();   
}
paragraph.setAlignment(ParagraphAlignment.LEFT);
run = paragraph.createRun();
pictureIn = new FileInputStream(&quot;./leftLogo.png&quot;);
run.addPicture(pictureIn, XWPFDocument.PICTURE_TYPE_PNG, &quot;leftLogo.png&quot;, Units.toEMU(80), Units.toEMU(80));
// right cell
cell = row.getCell(2);
if (cell.getParagraphs().size() &gt; 0) {
paragraph = cell.getParagraphs().get(0);
} else {
paragraph = cell.addParagraph();   
}
paragraph.setAlignment(ParagraphAlignment.RIGHT);
run = paragraph.createRun();
pictureIn = new FileInputStream(&quot;./rightLogo.png&quot;);
run.addPicture(pictureIn, XWPFDocument.PICTURE_TYPE_PNG, &quot;rightLogo.png&quot;, Units.toEMU(80), Units.toEMU(80));
// middle cell
cell = row.getCell(1);
if (cell.getParagraphs().size() &gt; 0) {
paragraph = cell.getParagraphs().get(0);
} else {
paragraph = cell.addParagraph();   
}
paragraph.setAlignment(ParagraphAlignment.CENTER);
run = paragraph.createRun();
run.setText(&quot;LOREM IPSUM SEMIT DOLOR SIT AMET&quot;);
run.addBreak();
run.setText(&quot;consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata&quot;);
// the footer content
// create footer start
XWPFFooter footer = doc.createFooter(HeaderFooterType.DEFAULT);
paragraph = footer.getParagraphArray(0);
if (paragraph == null) paragraph = footer.createParagraph();
paragraph.setAlignment(ParagraphAlignment.CENTER);
run = paragraph.createRun();  
run.setText(&quot;The Footer:&quot;);
// write out  
doc.write(out);
}
}
}

huangapple
  • 本文由 发表于 2023年7月17日 19:13:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/76703892.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定