首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Java中用OpenPDF居中/对齐表格中的文本

在Java中用OpenPDF居中/对齐表格中的文本
EN

Stack Overflow用户
提问于 2020-08-02 21:54:18
回答 1查看 767关注 0票数 1

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

我只了解到添加为table.addCell("sometext")的文本会将其居中对齐。因为我想添加更复杂的内容,这是不够的,我需要很好的定位控制。

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

代码语言:javascript
复制
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();
    }
}
EN

回答 1

Stack Overflow用户

发布于 2020-10-05 22:59:19

代码语言:javascript
复制
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);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63216815

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档