开发者

Working with columns and adding elements after

开发者 https://www.devze.com 2023-03-12 00:29 出处:网络
I\'m creating a pdf using the MultiColumnText ob开发者_如何学Pythonject within iTextSharp. The text carries over to the second page where it only fills the left column. So I have two questions:

I'm creating a pdf using the MultiColumnText ob开发者_如何学Pythonject within iTextSharp. The text carries over to the second page where it only fills the left column. So I have two questions:

1) Is it possible to fill in all three columns on the second page, and only take up as much vertical space as it requires?

2) Is it possible to add additional page elements after the column object ends without knocking the new elements over to a new page?


The only thing I can think of would be to "write out" your text into a ColumnText using go(true) to simulate layout and find out how tall your text really is (with no page breaks), and use that knowledge to construct columns with specific heights such that they'll be even.

This gets Really Difficult if your columns aren't all the same width.

Don't forget about the page's top & bottom margins when calculating how much room you have to work with.


Here is my solution to disperse the text equally among 3 columns on the final page.

The trick was to 1) simulate the code 2)find which column the code ended in 3)find how far down the page the text went 4)calculate the new 'bottom' 5)only apply the new 'bottom' to the final page of the non-simulated output

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;
    }

}
0

精彩评论

暂无评论...
验证码 换一张
取 消