public void createPDFFromText()

in tools/src/main/java/org/apache/pdfbox/tools/TextToPDF.java [250:407]


    public void createPDFFromText( PDDocument doc, Reader text ) throws IOException
    {
        // for some reason the font isn't initialized -> use default font
        if (font == null)
        {
            font = new PDType1Font(standardFont);
        }
        float fontHeight = font.getBoundingBox().getHeight() / FONTSCALE;
        PDRectangle actualMediaBox =
                landscape ? new PDRectangle(mediaBox.getHeight(), mediaBox.getWidth()) : mediaBox;

        // calculate line height and increase by a factor.
        float lineHeight = fontHeight * fontSize * lineSpacing;
        BufferedReader data = new BufferedReader(text);
        String nextLine;
        PDPage page = new PDPage(actualMediaBox);
        PDPageContentStream contentStream = null;
        float y = -1;
        float maxStringLength = page.getMediaBox().getWidth() - leftMargin - rightMargin;

        // There is a special case of creating a PDF document from an empty string.
        boolean textIsEmpty = true;

        StringBuilder nextLineToDraw = new StringBuilder();

        while ((nextLine = data.readLine()) != null)
        {
            // The input text is nonEmpty. New pages will be created and added
            // to the PDF document as they are needed, depending on the length of
            // the text.
            textIsEmpty = false;

            String[] lineWords = nextLine.replaceAll("[\\n\\r]+$", "").split(" ", -1);
            int lineIndex = 0;
            while (lineIndex < lineWords.length)
            {
                nextLineToDraw.setLength(0);
                boolean addSpace = false;
                float lengthIfUsingNextWord = 0;
                boolean ff = false;
                do
                {
                    String word1, word2 = "";
                    String word = lineWords[lineIndex];
                    int indexFF = word.indexOf('\f');
                    if (indexFF == -1)
                    {
                        word1 = word;
                    }
                    else
                    {
                        ff = true;
                        word1 = word.substring(0, indexFF);
                        if (indexFF < word.length())
                        {
                            word2 = word.substring(indexFF + 1);
                        }
                    }
                    // word1 is the part before ff, word2 after
                    // both can be empty
                    // word1 can also be empty without ff, if a line has many spaces
                    if (!word1.isEmpty() || !ff)
                    {
                        if (addSpace)
                        {
                            nextLineToDraw.append(' ');
                        }
                        else
                        {
                            addSpace = true;
                        }
                        nextLineToDraw.append(word1);
                    }
                    if (!ff || word2.isEmpty())
                    {
                        lineIndex++;
                    }
                    else
                    {
                        lineWords[lineIndex] = word2;
                    }
                    if (ff)
                    {
                        break;
                    }
                    if (lineIndex < lineWords.length)
                    {
                        // need cut off at \f in next word to avoid IllegalArgumentException
                        String nextWord = lineWords[lineIndex];
                        indexFF = nextWord.indexOf('\f');
                        if (indexFF != -1)
                        {
                            nextWord = nextWord.substring(0, indexFF);
                        }

                        String lineWithNextWord = nextLineToDraw + " " + nextWord;
                        lengthIfUsingNextWord
                                = (font.getStringWidth(lineWithNextWord) / FONTSCALE) * fontSize;
                    }
                }
                while (lineIndex < lineWords.length && lengthIfUsingNextWord < maxStringLength);

                if (y - lineHeight < bottomMargin)
                {
                    // We have crossed the end-of-page boundary and need to extend the
                    // document by another page.
                    page = new PDPage(actualMediaBox);
                    doc.addPage(page);
                    if (contentStream != null)
                    {
                        contentStream.endText();
                        contentStream.close();
                    }
                    contentStream = new PDPageContentStream(doc, page);
                    contentStream.setFont(font, fontSize);
                    contentStream.beginText();
                    y = page.getMediaBox().getHeight() - topMargin;
                    y += lineHeight - fontHeight * fontSize; // adjust for lineSpacing != 1
                    contentStream.newLineAtOffset(leftMargin, y);
                }

                if (contentStream == null)
                {
                    throw new IOException("Error:Expected non-null content stream.");
                }
                contentStream.newLineAtOffset(0, -lineHeight);
                y -= lineHeight;
                contentStream.showText(nextLineToDraw.toString());
                if (ff)
                {
                    page = new PDPage(actualMediaBox);
                    doc.addPage(page);
                    contentStream.endText();
                    contentStream.close();
                    contentStream = new PDPageContentStream(doc, page);
                    contentStream.setFont(font, fontSize);
                    contentStream.beginText();
                    y = page.getMediaBox().getHeight() - topMargin;
                    y += lineHeight - fontHeight * fontSize; // adjust for lineSpacing != 1
                    contentStream.newLineAtOffset(leftMargin, y);
                }
            }
        }

        // If the input text was the empty string, then the above while loop will have short-circuited
        // and we will not have added any PDPages to the document.
        // So in order to make the resultant PDF document readable by Adobe Reader etc, we'll add an empty page.
        if (textIsEmpty)
        {
            doc.addPage(page);
        }

        if (contentStream != null)
        {
            contentStream.endText();
            contentStream.close();
        }
    }