简体   繁体   English

内容较长时,itextsharp不会创建新页面

[英]itextsharp doesn't make new page when content is longer

I try from 3 day to find way to make one pdf document, and I will appreciate any help. 我尝试从3天开始寻找制作一个pdf文档的方法,我将不胜感激。

I have few form fields which access and fill with no problem. 我只有很少的表单字段可以访问和填写。 Below of this fields I want to place dynamically created table. 我要在此字段下方放置动态创建的表。 This table can be long enough to be on more than one page. 该表可能足够长,不能超过一页。 And here is my problem. 这是我的问题。 I can`t add this table on the same page with form fiels just below them. 我无法在同一页面上的表格字段下方添加此表格。 I find example which merge pdf files. 我找到合并pdf文件的示例。 And now I have this scenario. 现在我有这种情况。

  1. Make one pdf with filled form fields 用填写的表单域制作一个pdf
  2. Make pdf with pdfTable which always be with only one page, but content is longer 用pdfTable制作pdf,该pdfTable总是只有一页,但是内容更长
  3. Make pdf which is merge from first two. 制作从前两个合并的pdf。 In first page is filled form fields and in second page is my pdfTable. 在第一页中填写表格字段,在第二页中是我的pdfTable。

I just want to have form fields and table which starts from first page and continue on some next pages. 我只希望表单字段和表格从第一页开始,然后在下一页继续。

I post my code which is a little mess but ... 我发布我的代码有点混乱,但是...

string pdfTemplate = Server.MapPath("~/PDF/") + "invoiceTest.pdf";
        string newFile = Server.MapPath("~/PDF/") + "invoice" + 1 + ".pdf";

        using (FileStream ms = new FileStream(Server.MapPath("~/PDF/") + "invoice" + 1 + ".pdf", FileMode.Create))
        using (FileStream formFile = new FileStream(Server.MapPath("~/PDF/") + "invoiceTest.pdf", FileMode.Open))
        {
            PdfReader reader = new PdfReader(formFile);
            using (Document document = new Document(reader.GetPageSizeWithRotation(1)))
            {
                PdfStamper outStamper = new PdfStamper(reader, ms);
                PdfContentByte body = outStamper.GetOverContent(reader.NumberOfPages);

                document.Open(); //Open document to work with

                AcroFields fields = outStamper.AcroFields;

                BaseFont bfComic = BaseFont.CreateFont(Server.MapPath("~/PDF/") + "trebuc.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
                Font font = new Font(bfComic, 12);

                // UPDATE THE FORM FIELDS
                fields.SetFieldProperty("txtContragentName", "textfont", bfComic, null);
                fields.SetField("txtContragentName", "Фрея");
                fields.SetFieldProperty("txtContragentCode", "textfont", bfComic, null);
                fields.SetField("txtContragentCode", "DGB34TT");
                fields.SetFieldProperty("txtDateCreated", "textfont", bfComic, null);
                fields.SetField("txtDateCreated", "03.06.2013");

                outStamper.Close();
            }
        }

        using (FileStream ms = new FileStream(Server.MapPath("~/PDF/") + "invoice" + 2 + ".pdf", FileMode.Create))
        using (FileStream formFile = new FileStream(Server.MapPath("~/PDF/") + "invoice" + 1 + ".pdf", FileMode.Open))
        {
            PdfReader reader = new PdfReader(formFile);
            using (Document document = new Document(reader.GetPageSizeWithRotation(1)))
            {
                PdfWriter writer = PdfWriter.GetInstance(document, ms);
                document.Open();
                //Paragraph heading = new Paragraph("Page Heading", new Font(Font.FontFamily.HELVETICA, 10f, Font.BOLD));
                //heading.SpacingAfter = 8f;
                //doc.Add(heading);
                string text = @"Lorem 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?";
                PdfContentByte cb = writer.DirectContent;
                ColumnText columns = new ColumnText(cb);
                //float left, float right, float gutterwidth, int numcolumns
                columns.SetSimpleColumn(40, 20, document.PageSize.Width - 40, document.PageSize.Height - 20);
                //Paragraph para = new Paragraph(text, new Font(Font.FontFamily.HELVETICA, 8f));
                ////para.SpacingAfter = 9f;
                //para.Alignment = Element.ALIGN_JUSTIFIED;
                //for (int i = 0; i < 28; i++)
                //{
                //    columns.AddElement(para);
                //}

                //columns.Go();

                BaseFont bfComic = BaseFont.CreateFont(Server.MapPath("~/PDF/") + "trebuc.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
                Font font = new Font(bfComic, 12);
                PdfPTable table = new PdfPTable(10);
                table.HorizontalAlignment = Element.ALIGN_LEFT;
                table.DefaultCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                table.WidthPercentage = 100;
                PdfPCell cell1 = new PdfPCell(new Phrase("ДАТА", new Font(bfComic, 10f, Font.NORMAL, BaseColor.WHITE))) { HorizontalAlignment = 1, VerticalAlignment = 2 };
                cell1.BackgroundColor = new iTextSharp.text.BaseColor(System.Drawing.ColorTranslator.FromHtml("#808080"));

                PdfPCell cell2 = new PdfPCell(new Phrase("Header spanning 3 columns", new Font(Font.NORMAL, 10f, Font.NORMAL, BaseColor.WHITE))) { HorizontalAlignment = 1 };
                cell2.BackgroundColor = new iTextSharp.text.BaseColor(System.Drawing.ColorTranslator.FromHtml("#808080"));

                table.AddCell(cell1);
                table.AddCell(cell2);
                //dump data to be set
                #region dump data
                for (int i = 0; i < 100; i++)
                {
                    table.AddCell("Col 1 Row 1");
                }

                #endregion

                float[] widths = new float[] { 200f, 200f, 200f, 200f, 100f, 100f, 100f, 100f, 100f, 100f };
                table.SetWidths(widths);
                table.CompleteRow(); //Added - table won't add the final row if its cells are incomplete - safe to have it ending a table
                columns.AddElement(table);
                columns.Go();
            }
        }

        using (FileStream ms = new FileStream(Server.MapPath("~/PDF/") + "invoice" + 3 + ".pdf", FileMode.Create))
        using (FileStream stampedfile = new FileStream(Server.MapPath("~/PDF/") + "invoice" + 1 + ".pdf", FileMode.Open))
        using (FileStream appendfile = new FileStream(Server.MapPath("~/PDF/") + "invoice" + 2 + ".pdf", FileMode.Open))
        {
            PdfReader stampedContentReader = new PdfReader(stampedfile);
            PdfReader appendContentReader = new PdfReader(appendfile);

            using (Document document = new Document(stampedContentReader.GetPageSizeWithRotation(1)))
            {
                PdfCopy pdfCopy = new PdfCopy(document, ms);

                document.Open();

                for (int i = 1; i <= stampedContentReader.NumberOfPages; i++)
                    pdfCopy.AddPage(pdfCopy.GetImportedPage(stampedContentReader, i));

                for (int i = 1; i <= appendContentReader.NumberOfPages; i++)
                    pdfCopy.AddPage(pdfCopy.GetImportedPage(appendContentReader, i));
            }
        }

Your code is indeed a mess. 您的代码确实是一团糟。 I'll copy/paste it but please understand that I'm not a C# developer. 我将复制/粘贴它,但请理解我不是C#开发人员。 I only know Java and I know iText inside-out (I'm its original developer). 我只知道Java,而且从内到外都知道iText(我是它的原始开发人员)。

string pdfTemplate = Server.MapPath("~/PDF/") + "invoiceTest.pdf";
string newFile = Server.MapPath("~/PDF/") + "invoice" + 1 + ".pdf";

using (FileStream ms = new FileStream(Server.MapPath("~/PDF/") + "invoice" + 1 + ".pdf", FileMode.Create))
using (FileStream formFile = new FileStream(Server.MapPath("~/PDF/") + "invoiceTest.pdf", FileMode.Open))
{
    PdfReader reader = new PdfReader(formFile);
    // YOU DON'T NEED A DOCUMENT OBJECT HERE!
    // READ THE DOCUMENTATION!!!
    PdfStamper outStamper = new PdfStamper(reader, ms);
    AcroFields fields = outStamper.AcroFields;
    BaseFont bfComic = BaseFont.CreateFont(Server.MapPath("~/PDF/") + "trebuc.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
    // UPDATE THE FORM FIELDS
    fields.SetFieldProperty("txtContragentName", "textfont", bfComic, null);
    fields.SetField("txtContragentName", "Фрея");
    fields.SetFieldProperty("txtContragentCode", "textfont", bfComic, null);
    fields.SetField("txtContragentCode", "DGB34TT");
    fields.SetFieldProperty("txtDateCreated", "textfont", bfComic, null);
    fields.SetField("txtDateCreated", "03.06.2013");
    outStamper.Close();
}

using (FileStream ms = new FileStream(Server.MapPath("~/PDF/") + "invoice" + 2 + ".pdf", FileMode.Create))
using (FileStream formFile = new FileStream(Server.MapPath("~/PDF/") + "invoice" + 1 + ".pdf", FileMode.Open))
{
    PdfReader reader = new PdfReader(formFile);
    // I'm adding extra parameters to change the margins so that they match what you had when you defined your ColumnText object
    using (Document document = new Document(reader.GetPageSizeWithRotation(1), 40, 40, 20, 20))
    {
        PdfWriter writer = PdfWriter.GetInstance(document, ms);
        document.Open();
        // HEADERS ARE ADDED WITH PAGE EVENTS!!!
        // PLEASE READ ABOUT PAGE EVENTS IF YOU NEED PAGE HEADERS
        string text = @"Lorem 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?";
        BaseFont bfComic = BaseFont.CreateFont(Server.MapPath("~/PDF/") + "trebuc.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        Font font = new Font(bfComic, 12);
        PdfPTable table = new PdfPTable(10);
        // The next line doesn't make sense if the width percentage is 100%
        // table.HorizontalAlignment = Element.ALIGN_LEFT;
        table.DefaultCell.HorizontalAlignment = Element.ALIGN_RIGHT;
        table.WidthPercentage = 100;
        PdfPCell cell1 = new PdfPCell(new Phrase("ДАТА", new Font(bfComic, 10f, Font.NORMAL, BaseColor.WHITE))) { HorizontalAlignment = 1, VerticalAlignment = 2 };
        cell1.BackgroundColor = new iTextSharp.text.BaseColor(System.Drawing.ColorTranslator.FromHtml("#808080"));
        PdfPCell cell2 = new PdfPCell(new Phrase("Header spanning 3 columns", new Font(Font.NORMAL, 10f, Font.NORMAL, BaseColor.WHITE))) { HorizontalAlignment = 1 };
        cell2.BackgroundColor = new iTextSharp.text.BaseColor(System.Drawing.ColorTranslator.FromHtml("#808080"));
        table.AddCell(cell1);
        table.AddCell(cell2);
        //dump data to be set
        #region dump data
        for (int i = 0; i < 100; i++)
        {
            table.AddCell("Col 1 Row 1");
        }
        #endregion
        float[] widths = new float[] { 200f, 200f, 200f, 200f, 100f, 100f, 100f, 100f, 100f, 100f };
        table.SetWidths(widths);
        table.CompleteRow(); //Added - table won't add the final row if its cells are incomplete - safe to have it ending a table
        document.Add(table);
    }
}

The major mistake you made in the first part of your code, is introducing Document . 您在代码的第一部分中犯的主要错误是引入Document There's no need for that. 没有必要。 Please read chapter 6 of my book and take a look at the C# examples . 请阅读我的书的第6章 ,并查看C#示例

The major mistake you made in the second part is using ColumnText meaning you want to take control over the layout, but not knowing how to deal with that control. 您在第二部分中犯的主要错误是使用ColumnText这意味着您想控制布局,但不知道如何处理该控件。 If you use ColumnText , you need to ask the column if all content was consumed. 如果使用ColumnText ,则需要询问该列是否所有内容都已消耗。 If not, you need to create a new page yourself. 如果不是,则需要自己创建一个新页面。 This is all explained in chapter 3 of my book. 这一切都在我的书的第3章中进行了解释。

The third part looks OK (as far as I understand C#). 第三部分看起来还可以(据我所知C#)。

I wrote my books so that people can save time by writing correct code from the start. 我写书是为了使人们从一开始就可以通过编写正确的代码来节省时间。 I didn't write my books so that I have to copy/paste them on StackOverflow ;-) 我没有写书,所以我不得不将它们复制/粘贴到StackOverflow上;-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM