How to center a text using PDFBox

前端 未结 2 1013
逝去的感伤
逝去的感伤 2020-12-24 05:49

My question is very simple: how can I center a text on a PDF, using PDFBox?

I don\'t know the string in advance, I can\'t find the middle by trial. The

2条回答
  •  误落风尘
    2020-12-24 06:09

    Ok, I found the answer myself. Here is how to center some text on a page:

    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);
    // Deprecated, only before 2.0:
    // stream.moveTextPositionByAmount((page.getMediaBox().getWidth() - titleWidth) / 2, page.getMediaBox().getHeight() - marginTop - titleheight);
    // From 2.0 and beyond:
    stream.newLineAtOffset((page.getMediaBox().getWidth() - titleWidth) / 2, page.getMediaBox().getHeight() - marginTop - titleheight);
    stream.drawString(title);
    stream.endText();
    stream.close();
    

提交回复
热议问题