使用列并在之后添加元素

时间:2011-06-09 19:55:24

标签: itextsharp itext

我正在使用iTextSharp中的MultiColumnText对象创建一个pdf。文本转到第二页,它只填充左栏。所以我有两个问题:

1)是否可以填写第二页上的所有三列,并且只占用所需的垂直空间?

2)是否可以在列对象结束后添加其他页面元素而不将新元素敲入新页面?

2 个答案:

答案 0 :(得分:0)

我唯一能想到的就是使用go(true)将文本“写出”到ColumnText中来模拟布局并找出文本的真实高度(没有分页符),并使用该知识构建具有特定高度的列,使它们均匀。

如果您的列宽度不同,这将非常困难。

不要忘记页面的顶部&计算你需要多少空间时的底部边距。

答案 1 :(得分:0)

这是我的解决方案,将文本平均分散在最后一页的3列中。

诀窍是 1)模拟代码 2)找到代码结束的列 3)找到文本在页面下方的距离 4)计算新的'底部' 5)仅将新的“底部”应用于非模拟输出的最后一页

class Program
{
    static void Main(string[] args)
    {
        string fileName = "columntexttest.pdf";

        Document doc = new Document(PageSize.LETTER, 50, 50, 50, 50);
        PdfWriter pdfWrite = PdfWriter.GetInstance(doc, new FileStream(fileName, FileMode.Create));
        doc.Open();

        PdfContentByte cb = pdfWrite.DirectContent;
        ColumnText ct = new ColumnText(cb);

        //default values
        int colCount = 0;
        float bottom = doc.Bottom;
        int pageCount = 0;


        AddText(ct);
        CreateColumnText(doc, ct, ref bottom, true, ref pageCount, ref colCount); //simulation
        AddText(ct);
        CreateColumnText(doc, ct, ref bottom, false, ref pageCount, ref colCount); //non-simulation
        doc.Add(new Paragraph("testing new paragraph"));

        doc.Close();
        System.Diagnostics.Process.Start(fileName);
    }


    private static void CreateColumnText(Document doc, ColumnText ct, ref float bottom, bool simulate, ref int pageCount, ref int colCount)
    {
        //reseting variables for non-simulation
        int status = 0;
        int currentPage = 1;
        int currentColumn = 0;
        float tempBottom = bottom;
        float tempBottom2 = tempBottom;
        if (simulate) 
        {
            pageCount = 1;
        }

        //column attributes
        float gutter = 15f;
        float colwidth = (doc.Right - doc.Left - gutter * 2) / 3;


        while (ColumnText.HasMoreText(status))
        {
            //calculates the bottom Y
            if (simulate == false && currentPage == pageCount)
            {
                if (colCount == 1) //1 column on final page
                {
                    tempBottom2 = (doc.Top - tempBottom) / 3 + 6;
                    bottom = doc.Top - tempBottom2;
                }
                else if (colCount == 2) //2 columns on final page
                {
                    tempBottom2 = ((doc.Top - tempBottom) + doc.Top) / 3 + 6;
                    bottom = doc.Top - tempBottom2;
                }
                else if (colCount == 0) //0 colCount means 3 columns
                {
                    tempBottom2 = ((doc.Top - tempBottom) + doc.Top * 2) / 3 + 6;
                    bottom = doc.Top - tempBottom2;
                }
            }
            else
            {
                bottom = doc.Bottom; //default value for all pages except the last, or the value for a single page
            }

            if (currentColumn == 0) //writes first column
            {
                float[] left = {doc.Left, doc.Top, //top = 742 (true top is 792 then a 50 point margin)
                           doc.Left, bottom }; //bottom = 50

                float[] right = {doc.Left + colwidth, doc.Top,
                            doc.Left + colwidth, bottom};

                ct.SetColumns(left, right);
                currentColumn++;
            }
            else if (currentColumn == 1) //writes second column
            {
                float[] left2 = {doc.Left+ colwidth + gutter, doc.Top,
                            doc.Left + colwidth + gutter, bottom};

                float[] right2 = {doc.Right - colwidth - gutter, doc.Top,
                             doc.Right - colwidth - gutter, bottom};

                ct.SetColumns(left2, right2);
                currentColumn++;
            }

            else //writes third column
            {
                float[] left3 = { doc.Right - colwidth, doc.Top,
                            doc.Right- colwidth, bottom};

                float[] right3 = { doc.Right, doc.Top,
                             doc.Right, bottom};

                ct.SetColumns(left3, right3);
                currentColumn = 0;
            }

            status = ct.Go(simulate); //simulate mode

            if (currentColumn == 0 && status == 2) //creates new page only if text remains.
            {
                doc.NewPage();
                currentPage += 1;
            }
        }

        //values carry forward to non-simulation mode
        pageCount = currentPage;
        bottom = ct.YLine;
        colCount = currentColumn;
    }

    private static void AddText(ColumnText ct)
    {
        Font font2 = new Font(Font.NORMAL, 9f);
        ct.AddText(new Phrase("orem ipsum dolor sit amet, consectetuer adipiscing elit. Suspendisse blandit blandit turpis. Nam in lectus ut dolor consectetuer bibendum. Morbi neque ipsum, laoreet id; dignissim et, viverra id, mauris. Nulla mauris elit, consectetuer sit amet, accumsan eget, congue ac, libero. Vivamus suscipit. Nunc dignissim consectetuer lectus. Fusce elit nisi; commodo non, facilisis quis, hendrerit eu, dolor? Suspendisse eleifend nisi ut magna. Phasellus id lectus! Vivamus laoreet enim et dolor. Integer arcu mauris, ultricies vel, porta quis, venenatis at, libero. Donec nibh est, adipiscing et, ullamcorper vitae, placerat at, diam. Integer ac turpis vel ligula rutrum auctor! Morbi egestas erat sit amet diam. Ut ut ipsum? Aliquam non sem. Nulla risus eros, mollis quis, blandit ut; luctus eget, urna. Vestibulum vestibulum dapibus erat. Proin egestas leo a metus?\n\n", font2));
        ct.AddText(new Phrase("Vivamus enim nisi, mollis in, sodales vel, convallis a, augue? Proin non enim. Nullam elementum euismod erat. Aliquam malesuada eleifend quam! Nulla facilisi. Aenean ut turpis ac est tempor malesuada. Maecenas scelerisque orci sit amet augue laoreet tempus. Duis interdum est ut eros. Fusce dictum dignissim elit. Morbi at dolor. Fusce magna. Nulla tellus turpis, mattis ut, eleifend a, adipiscing vitae, mauris. Pellentesque mattis lobortis mi.\n\n", font2));
        ct.AddText(new Phrase("Nullam sit amet metus scelerisque diam hendrerit porttitor. Aenean pellentesque, lorem a consectetuer consectetuer, nunc metus hendrerit quam, mattis ultrices lorem tellus lacinia massa. Aliquam sit amet odio. Proin mauris. Integer dictum quam a quam accumsan lacinia. Pellentesque pulvinar feugiat eros. Suspendisse rhoncus. Sed consectetuer leo eu nisi. Suspendisse massa! Sed suscipit lacus sit amet elit! Aliquam sollicitudin condimentum turpis. Nunc ut augue! Maecenas eu eros. Morbi in urna consectetuer ipsum vehicula tristique.\n\n", font2));
        ct.AddText(new Phrase("Donec imperdiet purus vel ligula. Vestibulum tempor, odio ut scelerisque eleifend, nulla sapien laoreet dui; vel aliquam arcu libero eu ante. Curabitur rutrum tristique mi. Sed lobortis iaculis arcu. Suspendisse mauris. Aliquam metus lacus, elementum quis, mollis non, consequat nec, tortor.\n", font2));
        ct.AddText(new Phrase("Quisque id diam. Ut egestas leo a elit. Nulla in metus. Aliquam iaculis turpis non augue. Donec a nunc? Phasellus eu eros. Nam luctus. Duis eu mi. Ut mollis. Nulla facilisi. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Aenean pede. Nulla facilisi. Vestibulum mattis adipiscing nulla. Praesent orci ante, mattis in, cursus eget, posuere sed, mauris.\n\n", font2));
        ct.AddText(new Phrase("Nulla facilisi. Nunc accumsan risus aliquet quam. Nam pellentesque! Aenean porttitor. Aenean congue ullamcorper velit. Phasellus suscipit placerat tellus. Vivamus diam odio, tempus quis, suscipit a, dictum eu; lectus. Sed vel nisl. Ut interdum urna eu nibh. Praesent vehicula, orci id venenatis ultrices, mauris urna mollis lacus, et blandit odio magna at enim. Pellentesque lorem felis, ultrices quis, gravida sed, pharetra vitae, quam. Mauris libero ipsum, pharetra a, faucibus aliquet, pellentesque in, mauris. Cras magna neque, interdum vel, varius nec; vulputate at, erat. Quisque vitae urna. Suspendisse potenti. Nulla luctus purus at turpis! Vestibulum vitae dui. Nullam odio.\n\n", font2));
        ct.AddText(new Phrase("Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Sed eget mi at sem iaculis hendrerit. Nulla facilisi. Etiam sed elit. In viverra dapibus sapien. Aliquam nisi justo, ornare non, ultricies vitae, aliquam sit amet, risus! Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Phasellus risus. Vestibulum pretium augue non mi. Sed magna. In hac habitasse platea dictumst. Quisque massa. Etiam viverra diam pharetra ante. Phasellus fringilla velit ut odio! Nam nec nulla.\n\n", font2));
        ct.AddText(new Phrase("Integer augue. Morbi orci. Sed quis nibh. Nullam ac magna id leo faucibus ornare. Vestibulum eget lectus sit amet nunc facilisis bibendum. Donec adipiscing convallis mi. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Vivamus enim. Mauris ligula lorem, pellentesque quis, semper sed, tristique sit amet, justo. Suspendisse potenti. Proin vitae enim. Morbi et nisi sit amet sapien ve.", font2));

        ct.Alignment = Element.ALIGN_JUSTIFIED;
    }

}