如何使用PDFBox居中文本

时间:2011-06-28 13:22:28

标签: java pdfbox text-alignment

我的问题非常简单:如何使用PDFBox将文本置于PDF中心?

我提前不知道字符串,我找不到中间的试用版。字符串并不总是具有相同的宽度。

我需要:

  • 一种可以使文本居中的方法,例如addCenteredString(myString)
  • 一种方法,可以给出字符串的宽度(以像素为单位)。然后我可以计算中心,因为我知道PDF的尺寸。

欢迎任何帮助!

2 个答案:

答案 0 :(得分:57)

好的,我自己找到了答案。以下是如何在页面上居中显示某些文字:

String title = "This is my wonderful title!"; // Or whatever title you want.
int marginTop = 30; // Or whatever margin you want.

PDDocument document = new PDDocument();
PDPage page = new PDPage()
PDPageStreamContent stream = new PDPageContentStream(document, page);
PDFont font = PDType1Font.HELVETICA_BOLD; // Or whatever font you want.

int fontSize = 16; // Or whatever font size you want.
float titleWidth = font.getStringWidth(title) / 1000 * fontSize;
float titleHeight = font.getFontDescriptor().getFontBoundingBox().getHeight() / 1000 * fontSize;

stream.beginText();
stream.setFont(font, fontSize);
stream.moveTextPositionByAmount((page.getMediaBox().getWidth() - titleWidth) / 2, page.getMediaBox().getHeight - marginTop - titleheight);
stream.drawString(title);
stream.endText();
stream.close();

答案 1 :(得分:4)

这会将居中文字添加到纵向和横向格式的页面中:

PDDocument pdf = new PDDocument();
// A5 page in landscape format
PDPage page = new PDPage(PDRectangle.A5);
page.setRotation(90);

pdf.addPage(page);
try (PDPageContentStream content = new PDPageContentStream(pdf, page)) {
    int fontSize = 36;

    // Put the text at the page's center, no offset
    Point2D.Float center = new Point2D.Float(0, 0);
    addCenteredText("PDFBox", PDType1Font.HELVETICA_BOLD, fontSize, content, page, center);

    // Put the text centered at the lower end of the page
    Point2D.Float lowerCenter = new Point2D.Float(0, -165);
    addCenteredText("Hi there!", PDType1Font.HELVETICA, fontSize, content, page, lowerCenter);

} catch (IOException e) {
    LOG.warn("Exception while creating content", e);
}

这是在旋转页面上创建具有居中文本的PDF的方法:

/**
     * @Route("/upload/{inspection}")
     * @ParamConverter("inspection", class="AppBundle:Inspection")
     */
    public function uploadAction(Request $request, $inspection)
    {
        $file = $request->files->get('file');

        $fileEntity = new File();
        $fileEntity->setFileLink($file);

        $fileEntity->setInspection($inspection);

        $file_link = $this->get('app.entity.inspectionFiles')->handleUpload($fileEntity);

        $fileEntity->setFile($file_link);

        $inspection->addFile($fileEntity);

        $em = $this->getDoctrine()->getManager();

        $em->persist($fileEntity);
        $em->flush();

        return new Response();
    }

生成的PDF:

resulting PDF

我使用PDFBox 2.0.0-RC2来创建此PDF。