在iText / Java中的PdfPtable中没有换行的文本

时间:2014-07-08 08:07:28

标签: java pdf itext pdfptable

我在iText(版本4.2.0)中遇到了PdfPTable的问题。我计算每列的最大宽度(取决于这个地方的托管)。在此之后我给出方法PdfPTable.setWidths()这些值。

现在问题是,如果我有很多列,iText必须将这些列扩展到第二页,它会破坏旁边的相关列宽(文本将换行)。

我的目的地是文本不会换行。文本应该在一行中(这就是我计算columnwidt的原因)。

以上是代码,这是有效的。

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map.Entry;

import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Font;
import com.lowagie.text.PageSize;
import com.lowagie.text.Phrase;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfWriter;

public class PdfTest
{
    public static final String RESULT = "C:\\Users\\user\\Documents\\tableTest.pdf";

    /**
     * Creates a PDF document.
     * 
     * @param filename
     *            the path to the new PDF document
     * @throws DocumentException
     * @throws IOException
     */
    public void createPdf(String filename) throws IOException, DocumentException
    {
        // ---- Test-Entrys ----
        final String[] earningsSpecial =
        {
                "Objectiv-C", "Java", "C#", "C++", "Eclipse", "Stackoverflow", "Netbeans", "BugTracker", "iText", "Table-Test", "Mac OS X", "Linux", "Microsoft", "Android", "News", "About", "iTest", "Create PDF"
        };
        final ArrayList<String[]> list = new ArrayList<>();
        list.add(earningsSpecial);
        // ---------------------

        final Document document = new Document();
        final PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
        final Font myFont = new Font(Font.TIMES_ROMAN, 12);

        document.setPageSize(PageSize.A4.rotate());
        Rectangle rec = document.getPageSize();

        final float pageWidth = rec.getWidth();
        final float pageHeight = rec.getHeight();

        // 50 for left, 50 for right
        final float finalPageWidth = pageWidth - 100;
        // just works for the top, bottom is another TODO
        final float finalPageHeight = pageHeight - 50;

        document.open();

        final String[] entriesValueSpace = init(list);

        final HashMap<Integer, ArrayList<Float>> tmpCalcList = calculateRowSpans(entriesValueSpace, pageWidth - 100);

        final PdfPTable table = new PdfPTable(entriesValueSpace.length);

        table.setWidthPercentage(90);
        table.setTotalWidth(finalPageWidth);

        // This are the calculated column widths (this comes from the method
        // calculateRowSpans). It's only for the test too.
        float[] tmpfloatCalcList =
        {
                56.004005f, 25.344f, 15.336001f, 22.68f, 38.676003f, 74.688f, 51.36f, 62.016003f, 26.004002f, 57.348003f, 54.684002f, 28.68f, 48.672005f, 41.352f, 30.0f, 31.356003f, 26.004002f, 63.348003f
        };

        int[] tmpCalcVerhColumn = new int[tmpfloatCalcList.length];

        // With this i would calculate the proportion of each column to the
        // total pageWidth (not the finalPageWidth (finalPageWidth =
        // pageWidth-100)).
        for (int i = 0; i < tmpfloatCalcList.length; i++)
        {
            tmpCalcVerhColumn[i] = (int) ((tmpfloatCalcList[i] * 100) / pageWidth);
        }

        table.setWidths(tmpCalcVerhColumn);

        for (String[] movie : list)
        {
            for (String string : movie)
            {
                table.addCell(new PdfPCell(new Phrase(string, myFont)));
            }
        }

        PdfContentByte canvas = writer.getDirectContent();

        int tillThenPosition = 0;
        int lastPosition = 0;

        for (Entry<Integer, ArrayList<Float>> entry : tmpCalcList.entrySet())
        {
            tillThenPosition += entry.getValue().size();
            table.writeSelectedRows(lastPosition, tillThenPosition, 0, -1, 50, finalPageHeight, canvas);
            document.setPageSize(PageSize.A4.rotate());
            document.newPage();
            lastPosition = tillThenPosition;
        }

        document.close();
    }

    /**
     * Calculate the longest entry from each String [] in the list. With this i
     * prevent a line break in the table.
     * 
     * @param entrys
     * @return
     */
    private String[] init(final ArrayList<String[]> entrys)
    {
        String[] entryLength = null;
        for (String[] earning : entrys)
        {
            if (entryLength == null)
            {
                entryLength = new String[earning.length];
            }

            for (int i = 0; i < earning.length; i++)
            {
                if (entryLength[i] == null || entryLength[i].length() < earning[i].length())
                {
                    entryLength[i] = earning[i];
                }
            }
        }
        return entryLength;
    }

    /**
     * This method calculate the span for each column and save it in a map. A
     * map because with this it's possible to know how much sites with
     * associated columnswidth are available.
     * 
     * @param entriesValueSpace
     * @param pageWidth
     * @return
     * @throws DocumentException
     * @throws IOException
     */
    private HashMap<Integer, ArrayList<Float>> calculateRowSpans(final String[] entriesValueSpace, float pageWidth) throws DocumentException, IOException
    {
        HashMap<Integer, ArrayList<Float>> calculatedRowSpan = new HashMap<>();
        float widthPoint;
        float pageWidthCounter = 0;
        int counter = 0;
        ArrayList<Float> sizesPerPage = new ArrayList<>();
        BaseFont bf = BaseFont.createFont();

        for (String entry : entriesValueSpace)
        {
            widthPoint = bf.getWidthPoint(entry, 12);
            sizesPerPage.add(widthPoint);
            pageWidthCounter += widthPoint;

            if (pageWidthCounter > pageWidth - 100)
            {
                calculatedRowSpan.put(counter, sizesPerPage);
                counter++;
                pageWidthCounter = 0;
                sizesPerPage = new ArrayList<>();
            }
        }

        calculatedRowSpan.put(counter, sizesPerPage);

        return calculatedRowSpan;
    }

    public static void main(String[] args) throws IOException, DocumentException
    {
        new PdfTest().createPdf(RESULT);
    }

}

任何建议都应该是好的,提前谢谢。

0 个答案:

没有答案