iTextSharp - добавить верхний / нижний колонтитул в PDF - PullRequest
2 голосов
/ 10 апреля 2020

Это мой первый вопрос по stackoverflow .

Я надеюсь, что это будет приветствоваться.

Мой вопрос.

Я пытаюсь использовать iTextSharp для создания PDF-файла с верхним и нижним колонтитулами, количеством страниц и lo go.

Мой код приведен ниже, и моя проблема - ошибка в этой строке моего кода:

pdfDoc.Close();

Если я отключу эту строку, файл PDF будет создан, но он не сможет открыть поврежденный файл.

Ошибка:

Object reference not set to an instance of an object

Очень надеюсь на вашу помощь.

Создание файла PDF:

using (StringWriter sw = new StringWriter())
{
    using (HtmlTextWriter hw = new HtmlTextWriter(sw))
    {
        pdffile.RenderControl(hw);

        StringReader sr = new StringReader(sw.ToString());
        string imagepath = Server.MapPath("..") + "\\Logo.jpg";
        Document pdfDoc = new Document(PageSize.A4, 20f, 20f, 10f, 20f);

        using (MemoryStream memoryStream = new MemoryStream())
        {
            try
            {
                PdfWriter writer = PdfWriter.GetInstance(pdfDoc, memoryStream);
                pdfDoc.Open();
                writer.PageEvent = new Footer();
                BaseFont bfTimes = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false);
                iTextSharp.text.Font times = new iTextSharp.text.Font(bfTimes, 12, iTextSharp.text.Font.ITALIC, iTextSharp.text.BaseColor.MAGENTA);

                iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(imagepath);
                pdfDoc.Add(image);

                var cssResolver = new StyleAttrCSSResolver();
                var cssFile = XMLWorkerHelper.GetCSS(new FileStream(HttpContext.Current.Server.MapPath("style.css"), FileMode.Open));
                cssResolver.AddCss(cssFile);

                // HTML  
                HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);
                htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());

                // Pipelines  
                PdfWriterPipeline pdfFile = new PdfWriterPipeline(pdfDoc, writer);
                HtmlPipeline html = new HtmlPipeline(htmlContext, pdfFile);
                CssResolverPipeline css = new CssResolverPipeline(cssResolver, html);

                // XML Worker  
                XMLWorker worker = new XMLWorker(css, true);
                XMLParser p = new XMLParser(worker);
                p.Parse(sr);

                pdfDoc.Close();
                byte[] bytes = memoryStream.ToArray();
                memoryStream.Close();

            }
            catch (Exception ex)
            {
                throw (ex);
            }
        }
    }
}

Добавление верхнего / нижнего колонтитула в PDF

public partial class Footer : PdfPageEventHelper
{
    PdfContentByte cb;
    PdfTemplate headerTemplate, footerTemplate;
    BaseFont bf = null;
    DateTime PrintTime = DateTime.Now;
    iTextSharp.text.Image image;
    private string _header;

    public string Header
    {
        get { return _header; }
        set { _header = value; }
    }

    public override void OnOpenDocument(PdfWriter writer, Document document)
    {
        try
        {
            PrintTime = DateTime.Now;
            bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
            cb = writer.DirectContent;
            headerTemplate = cb.CreateTemplate(100, 100);
            footerTemplate = cb.CreateTemplate(50, 50);

        }
        catch (DocumentException de)
        {
            //handle exception here
        }
        catch (System.IO.IOException ioe)
        {
            //handle exception here
        }
    }

    public override void OnEndPage(iTextSharp.text.pdf.PdfWriter writer,
        iTextSharp.text.Document document)
    {
        base.OnEndPage(writer, document);

        iTextSharp.text.Font baseFontNormal =
            new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12f,
            iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK);

        iTextSharp.text.Font baseFontBig =
            new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12f,
            iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.BLACK);

        Phrase p1Header = new Phrase("testing", baseFontNormal);
        PdfPTable pdfTab = new PdfPTable(3);
        PdfPCell pdfCell1 = new PdfPCell();
        PdfPCell pdfCell2 = new PdfPCell(p1Header);
        PdfPCell pdfCell3 = new PdfPCell();
        String text = "Page " + writer.PageNumber + " of ";

        {

            cb.BeginText();
            cb.SetFontAndSize(bf, 12);
            cb.SetTextMatrix(document.PageSize.GetRight(200), document.PageSize.GetTop(45));
            cb.ShowText(text);
            cb.EndText();
            float len = bf.GetWidthPoint(text, 12);
            cb.AddTemplate(headerTemplate, document.PageSize.GetRight(200) + len, document.PageSize.GetTop(45));
        }

        {
            cb.BeginText();
            cb.SetFontAndSize(bf, 12);
            cb.SetTextMatrix(document.PageSize.GetRight(180), document.PageSize.GetBottom(30));
            cb.ShowText(text);
            cb.EndText();
            float len = bf.GetWidthPoint(text, 12);
            cb.AddTemplate(footerTemplate, document.PageSize.GetRight(180) + len, document.PageSize.GetBottom(30));

            Paragraph footer =
                new Paragraph("©All Rights Reserved",
                FontFactory.GetFont(FontFactory.HELVETICA, 8, iTextSharp.text.Font.ITALIC));
            footer.Alignment = Element.ALIGN_RIGHT;
            PdfPTable footerTbl = new PdfPTable(1);
            footerTbl.TotalWidth = 800;
            footerTbl.HorizontalAlignment = Element.ALIGN_CENTER;
            PdfPCell cell = new PdfPCell(footer);
            cell.Border = 0;
            cell.PaddingLeft = 10;
            footerTbl.AddCell(cell);
            footerTbl.WriteSelectedRows(0, -1, 0, 30, writer.DirectContent);
        }

        PdfPCell pdfCell4 = new PdfPCell(new Phrase("test", baseFontNormal));
        PdfPCell pdfCell5 = new PdfPCell(new Phrase("Date:" + PrintTime.ToShortDateString(), baseFontBig));
        PdfPCell pdfCell6 = new PdfPCell();
        PdfPCell pdfCell7 = new PdfPCell(new Phrase("Hour:" + string.Format("{0:t}", DateTime.Now), baseFontBig));

        pdfCell1.HorizontalAlignment = Element.ALIGN_CENTER;
        pdfCell2.HorizontalAlignment = Element.ALIGN_CENTER;
        pdfCell3.HorizontalAlignment = Element.ALIGN_CENTER;
        pdfCell4.HorizontalAlignment = Element.ALIGN_CENTER;
        pdfCell5.HorizontalAlignment = Element.ALIGN_CENTER;
        pdfCell6.HorizontalAlignment = Element.ALIGN_CENTER;
        pdfCell7.HorizontalAlignment = Element.ALIGN_CENTER;


        pdfCell2.VerticalAlignment = Element.ALIGN_BOTTOM;
        pdfCell3.VerticalAlignment = Element.ALIGN_MIDDLE;
        pdfCell4.VerticalAlignment = Element.ALIGN_TOP;
        pdfCell5.VerticalAlignment = Element.ALIGN_MIDDLE;
        pdfCell6.VerticalAlignment = Element.ALIGN_MIDDLE;
        pdfCell7.VerticalAlignment = Element.ALIGN_MIDDLE;


        pdfCell4.Colspan = 3;

        pdfCell1.Border = 0;
        pdfCell2.Border = 0;
        pdfCell3.Border = 0;
        pdfCell4.Border = 0;
        pdfCell5.Border = 0;
        pdfCell6.Border = 0;
        pdfCell7.Border = 0;

        pdfTab.AddCell(pdfCell1);
        pdfTab.AddCell(pdfCell2);
        pdfTab.AddCell(pdfCell3);
        pdfTab.AddCell(pdfCell4);
        pdfTab.AddCell(pdfCell5);
        pdfTab.AddCell(pdfCell6);
        pdfTab.AddCell(pdfCell7);

        pdfTab.TotalWidth = document.PageSize.Width - 80f;
        pdfTab.WidthPercentage = 70;

        pdfTab.WriteSelectedRows(0, -1, 40, document.PageSize.Height - 30, writer.DirectContent);

        cb.MoveTo(40, document.PageSize.Height - 100);
        cb.LineTo(document.PageSize.Width - 40, document.PageSize.Height - 100);
        cb.Stroke();

        cb.MoveTo(40, document.PageSize.GetBottom(50));
        cb.LineTo(document.PageSize.Width - 40, document.PageSize.GetBottom(50));
        cb.Stroke();
    }

    public override void OnCloseDocument(PdfWriter writer, Document document)
    {
        base.OnCloseDocument(writer, document);

        headerTemplate.BeginText();
        headerTemplate.SetFontAndSize(bf, 12);
        headerTemplate.SetTextMatrix(0, 0);
        headerTemplate.ShowText((writer.PageNumber - 1).ToString());
        headerTemplate.EndText();

        footerTemplate.BeginText();
        footerTemplate.SetFontAndSize(bf, 12);
        footerTemplate.SetTextMatrix(0, 0);
        footerTemplate.ShowText((writer.PageNumber - 1).ToString());
        footerTemplate.EndText();
    }
}

1 Ответ

0 голосов
/ 11 апреля 2020

Добро пожаловать, "Дядя Винс"!

Посмотрите это

И попробуйте это решение.

Надеюсь, я вам помог.

    MemoryStream memoryStream = new MemoryStream();
    StringWriter sw = new StringWriter();
    HtmlTextWriter hw = new HtmlTextWriter(sw);
    pdffile.RenderControl(hw);

    StringReader sr = new StringReader(sw.ToString());
    string imagepath = Server.MapPath("..") + "\\Logo.jpg";
    Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 100f, 0f);

    PdfWriter writer = PdfWriter.GetInstance(pdfDoc, memoryStream);
    writer.PageEvent = new Footer();
    BaseFont bfTimes = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false);
    iTextSharp.text.Font times = new iTextSharp.text.Font(bfTimes, 12, iTextSharp.text.Font.ITALIC, iTextSharp.text.BaseColor.MAGENTA);

    pdfDoc.Open();
    iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(imagepath);
    pdfDoc.Add(image);

    var cssResolver = new StyleAttrCSSResolver();
    var cssFile = XMLWorkerHelper.GetCSS(new FileStream(HttpContext.Current.Server.MapPath("style.css"), FileMode.Open));
    cssResolver.AddCss(cssFile);

    //HTML  
    HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);
    htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());

    //Pipelines  
    PdfWriterPipeline pdfFile = new PdfWriterPipeline(pdfDoc, writer);
    HtmlPipeline html = new HtmlPipeline(htmlContext, pdfFile);
    CssResolverPipeline css = new CssResolverPipeline(cssResolver, html);

    //XML Worker  
    XMLWorker worker = new XMLWorker(css, true);
    XMLParser p = new XMLParser(worker);

    p.Parse(sr);
    writer.CloseStream = false;
    pdfDoc.Close();
    memoryStream.Close();
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...