同样 Space Apache PDF Box PDF 创建中的字符

Equally Space the characters in Apache PDF Box PDF creation

我正在尝试使用 Apache PDFBox 创建 PDF 文件,内容是每行 80 个字符的纯文本消息。当我尝试创建 PDF 时,我注意到 space 、 _ 和其他字符在行中占据不同的宽度,我无法像在文本编辑器中那样对它们进行同样的格式化。有人可以帮我格式化吗?

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDDocumentInformation;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.font.PDType1Font;


public class SampleTest {
    public static void main(String[] args) throws Exception {
        PDDocument document = new PDDocument();     
        PDPage page = new PDPage(PDRectangle.A4);
        document.addPage(page);     
        String text =   "---------------------------\n" +
                        "------------ABC------------\n" +
                        "A                         B\n" +
                        "***************************\n" +   
                        "A  B  C  D  E  F  G  H  I  \n" +
                        "---------------------------";
        String[] textArray = text.split("\n");

        PDPageContentStream contentStream = new PDPageContentStream(document, page);        
        contentStream.beginText();      
        contentStream.setFont( PDType1Font.TIMES_ROMAN, 10 );
        contentStream.setLeading(4f);
        contentStream.newLineAtOffset(40, 750);  

        for(String line : textArray){
            contentStream.showText(line);
            contentStream.newLine();
            contentStream.newLine();    
        }
        contentStream.endText();
        contentStream.close();

        document.save("C:\PDF-Samples\file.pdf");
        document.close();
        System.out.println("Done");
    }
}

为此,您需要将字体更改为固定宽度的字体(如 PDType1Font.html.COURIER)。

一些阅读:https://en.wikipedia.org/wiki/Monospaced_font


要计算文本宽度,您可以使用:

// result in unit of text space, suitable to use with moveTextPositionByAmount()
(font.getStringWidth(text) / 1000.0f) * (1.0f * fontSize) // font is a PDFont