如何用java中的pdfbox在多个页面上写内容?

时间:2016-02-29 13:56:04

标签: java pdf pdfbox

我想从.txt文件中提取所有内容,然后创建一个包含确切内容的pdf文件。问题是我的程序只适用于1页内容,我不知道如何使它适用于多个页面。这就是我到目前为止所做的:

public class Controller {

    private int margin = 20;
    private PDPage page = new PDPage();

public void createPDF(File file) {
    String content = readFileContent(file);
    PDDocument doc = new PDDocument();
    PDFont font = PDType1Font.HELVETICA;
    int fontSize = 10;
    int lineHeigh = 5;
    PDRectangle mediabox = page.findMediaBox();
    float width = mediabox.getWidth() - 2 * margin;
    float startX = mediabox.getLowerLeftX() + margin;
    float startY = mediabox.getUpperRightY() - margin;

    try {
        PDPageContentStream contentStream = new PDPageContentStream(doc, page);
        drawMultiLineText(content, startX, startY, width, page, contentStream, font, fontSize, lineHeigh);
    } catch (IOException e) {
        e.printStackTrace();
    }
}


private void drawMultiLineText(String text, float x, float y, float allowedWidth, PDPage page,
                               PDPageContentStream contentStream, PDFont font, int fontSize, int lineHeight) throws IOException {

    List<String> lines = new ArrayList<String>();

    String myLine = "";

    // get all words from the text
    String[] words = text.split(" ");
    for (String word : words) {

        if (!myLine.isEmpty()) {
            myLine += " ";
        }

        // test the width of the current line + the current word
        int size = (int) (fontSize * font.getStringWidth(myLine + word) / 1000);
        if (size > allowedWidth) {
            // if the line would be too long with the current word, add the line without the current word
            lines.add(myLine);

            // and start a new line with the current word
            myLine = word;
        } else {
            // if the current line + the current word would fit, add the current word to the line
            myLine += word;
        }
    }
    // add the rest to lines
    lines.add(myLine);
    for (String line : lines) {
        contentStream.beginText();
        contentStream.setFont(font, fontSize);
        contentStream.moveTextPositionByAmount(x, y);
        contentStream.drawString(line);
        contentStream.endText();

        y -= lineHeight;
    }
}

0 个答案:

没有答案