如何使用iTextSharp将标题打印到.pdf文档中?

时间:2017-07-01 20:40:40

标签: header itext pdf-generation

我将this java code转换为C#,但由于我的.pdf文档中没有标题,我显然遗漏了一些东西。

这是转换后的代码:

public HttpResponseMessage CreatePdf()
        {
            HeaderTable HeaderTable = new HeaderTable();
            //  step 1
            Document document = new Document(PageSize.A4, 36, 36, 20 + HeaderTable.getTableHeight(), 36);
            //  step 2
            var memoryStream = new MemoryStream();
            PdfWriter writer = PdfWriter.GetInstance(document, memoryStream);
            writer.CloseStream = false;

            writer.PageEvent = HeaderTable;
            //  step 3
            document.Open();
            //  step 4
            for (int i = 0; (i< 50); i++) {
                document.Add(new Paragraph("Hello World!"));
            }

            document.NewPage();
            document.Add(new Paragraph("Hello World!"));
            document.NewPage();
            document.Add(new Paragraph("Hello World!"));
            //  step 5
            document.Close();

            memoryStream.Seek(0, SeekOrigin.Begin);

            return new HttpResponseMessage
            {
                Content = new StreamContent(memoryStream)
                {
                    Headers =
                    {
                        ContentType = new MediaTypeHeaderValue("application/pdf"),
                        ContentDisposition = new ContentDispositionHeaderValue("attachment")
                        {
                            FileName = "TEST.pdf"
                        }
                    }
                },
                StatusCode = HttpStatusCode.OK
            };
        }

        public class HeaderTable : PdfPageEventHelper
        {
            protected PdfPTable table;

            protected float tableHeight;

            public HeaderTable()
            {
                table = new PdfPTable(1);
                table.TotalWidth = 523;
                table.LockedWidth = true;
                table.AddCell("Header row 1");
                table.AddCell("Header row 2");
                table.AddCell("Header row 3");
                tableHeight = table.TotalHeight;
            }

            public float getTableHeight()
            {
                return tableHeight;
            }

            public void onEndPage(PdfWriter writer, Document document)
            {
                table.WriteSelectedRows(0, -1, document.Left, (document.Top + ((document.TopMargin + tableHeight) / 2)), writer.DirectContent);
            }
        }

我确定我犯了一个小错误,但我还没找到。请帮忙。

1 个答案:

答案 0 :(得分:0)

好的,我明白了。 而不是:

public class HeaderTable : PdfPageEventHelper

public void onEndPage(PdfWriter writer, Document document)

我应该写:

public partial class HeaderTable : PdfPageEventHelper

public override void OnEndPage(PdfWriter writer, Document document)