【问题标题】:Center/Align text in table cell with OpenPDF in Java使用Java中的OpenPDF居中/对齐表格单元格中的文本
【发布时间】:2020-11-22 18:36:04
【问题描述】:

我正在使用带有 Java 的 OpenPDF 1.3.20,并且想要更改表格单元格中文本/段落的对齐方式。 到目前为止,无论我尝试什么,都改变了文本在任何地方的位置。

我只知道添加为 table.addCell("sometext") 的文本会将其对齐为中心。 由于我想添加更复杂的内容,这还不够,我需要很好地控制定位。

这是我目前使用的测试类。如何更改特定单元格的对齐方式?

import com.lowagie.text.*;
import com.lowagie.text.Font;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfWriter;

import java.awt.*;
import java.io.FileOutputStream;
import java.io.IOException;

public class test {
    public static void main(String[] args){
        Document document = new Document();
        try {
            // step 2:
            // we create a writer that listens to the document
            // and directs a PDF-stream to a file
            PdfWriter.getInstance(document,
                    new FileOutputStream("HelloWorld.pdf"));

            // step 3: we open the document
            document.open();
            // step 4: we add a table to the document

            Font whiteFont = new
                    Font(Font.HELVETICA, 18, Font.NORMAL, new Color(255, 255, 255));
            PdfPTable table = new PdfPTable(2);
            table.setWidthPercentage(100);
            Color blue = new Color(0, 0, 255);

            PdfPCell cell = new PdfPCell();
            cell.setBorderWidth(0);
            cell.setBackgroundColor(blue);
            // here i try to change the alignment of text in the cell
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            Paragraph p = new Paragraph("test1", whiteFont);
            p.setAlignment(Element.ALIGN_MIDDLE);
            cell.addElement(p);
            table.addCell(cell);

            cell = new PdfPCell();
            cell.setBorderWidth(0);
            cell.setBackgroundColor(blue);
            cell.addElement(new Paragraph("test2", whiteFont));
            table.addCell(cell);

            document.add(table);
            document.close();

        } catch (DocumentException de) {
            System.err.println(de.getMessage());
        } catch (IOException ioe) {
            System.err.println(ioe.getMessage());
        }

        // step 5: we close the document
        document.close();
    }
}

【问题讨论】:

  • 这里有任何消息,我今天偶然发现了同样的问题。

标签: java pdf alignment openpdf


【解决方案1】:
Font whiteFont = new Font(Font.HELVETICA, 18, Font.NORMAL, new Color(255, 255, 255));



Phrase phrase = new Phrase("Hello World!", whiteFont);
PdfPCell cell = new PdfPCell(phrase);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setVerticalAlignment(Element.ALIGN_CENTER);

【讨论】:

  • 一般来说,如果答案包含对代码的用途的解释,以及为什么在不介绍其他人的情况下解决问题的原因,答案会更有帮助。
猜你喜欢
  • 2021-07-18
  • 2012-11-07
  • 1970-01-01
  • 2014-01-10
  • 1970-01-01
  • 2011-11-30
  • 1970-01-01
  • 2014-09-20
  • 2017-11-11
相关资源
最近更新 更多