是否可以使用iTextSharp在页边空白处打印

本文关键字:空白处 打印 可以使 iTextSharp 是否 | 更新日期: 2023-09-27 18:26:40

我正在编写一个输出PDF的web应用程序。我PDF的主要内容是一个表格数据。我想在表格左右两侧的空白处显示一条信息。

考虑到表格可能会跨越几页,我该如何做到这一点?

是否可以使用iTextSharp在页边空白处打印

最简单的方法可能是使用页面事件。要使用页面事件,您需要将PdfPageEventHelper:划分为子类

Public Class CustomPageEventHandler
    Inherits iTextSharp.text.pdf.PdfPageEventHelper
End Class

父类有一组可以重写的方法,您可能想要的方法是OnStartPage()。通过覆盖此项,将为文档中的每一页调用自定义代码。

Public Class CustomPageEventHandler
    Inherits iTextSharp.text.pdf.PdfPageEventHelper
    Public Overrides Sub OnStartPage(writer As iTextSharp.text.pdf.PdfWriter, document As iTextSharp.text.Document)
        ''//Anything you do here will be done on every page
    End Sub
End Class

要将自定义页面事件处理程序绑定到名为writerPdfWriter对象,只需执行以下操作:

writer.PageEvent = New CustomPageEventHandler()

至于在OnStartPage()方法中要做什么,您有几个选择。不幸的是,使用Document对象本身可能会出现问题。这个对象是用来处理更高级别概念的抽象,但并不总是提供在特定x、y坐标下做事的方法。在这里与文本一起使用只会导致文本奇怪地流动。

相反,您将希望使用一个原始PdfContentByte对象,该对象可以从writerDirectContent属性中获得。

Dim cb = writer.DirectContent

一旦你有了这些,你就有了几个选择,我会给你看两个。第一种是使用ColumnText对象,您可以将其视为一个表。事实上,大多数人将它用作单行、单列表。ColumnText对象很好,因为它允许您使用更高级别的抽象,如Paragraph,并且它将自动处理换行之类的事情。

Dim CT As New ColumnText(writer.DirectContent)
CT.SetSimpleColumn(llx, lly, urx, ury) ''//Coordinates to draw text to
CT.AddElement(New Paragraph("This goes in the margin"))
CT.Go()

第二种选择是自己绘制文本。这样做的最大缺点是不能使用像Paragraph这样的高级抽象。因此,如果你画了一条很长的文本线,它不会打断它并为你开始一条新行,它会在可视文档之外继续绘制。

Dim cb = writer.DirectContent
cb.BeginText()
cb.SetFontAndSize(BaseFont.CreateFont(BaseFont.TIMES_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED), 8)
cb.SetColorFill(BaseColor.RED)
cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "right margin", x, y, 0)
cb.EndText()

综上所述,下面是一个完整的VB.Net 2010 WinForm应用程序,它以iTextSharp 5.1.2.0为目标,展示了以上所有内容。有关具体详细信息,请参阅代码中的注释。

Option Strict On
Option Explicit On
Imports System.IO
Imports iTextSharp.text
Imports iTextSharp.text.pdf
Public Class Form1
    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        ''//Test file that we'll create
        Dim TestFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "TestFile.pdf")
        ''//Standard PDF setup, change as needed for your stream type
        Using FS As New FileStream(TestFile, FileMode.Create, FileAccess.Write, FileShare.None)
            Using Doc As New Document(PageSize.LETTER)
                Using writer = PdfWriter.GetInstance(Doc, FS)
                    ''//Bind our custom event handler to our writer object
                    writer.PageEvent = New CustomPageEventHandler()
                    Doc.Open()
                    ''//Add text on page 1
                    Doc.Add(New Paragraph("Page 1"))
                    ''//Add a new page
                    Doc.NewPage()
                    ''//Add text on page 2
                    Doc.Add(New Paragraph("Page 2"))
                    Doc.Close()
                End Using
            End Using
        End Using
        Me.Close()
    End Sub
    Public Class CustomPageEventHandler
        Inherits iTextSharp.text.pdf.PdfPageEventHelper
        ''//This will get called whenever a new page gets added to the document
        Public Overrides Sub OnStartPage(writer As iTextSharp.text.pdf.PdfWriter, document As iTextSharp.text.Document)
            ''//Pre-calculate the Y coordinates for use later
            Dim yBot = document.PageSize.Height - 300
            Dim yTop = yBot + 200
            ''//For the left margin we'll use the ColumnText object
            Dim CT As New ColumnText(writer.DirectContent)
            ''//Create a single column object bound to our margin and using the y coordinates from above
            CT.SetSimpleColumn(0, yBot, document.LeftMargin, yTop)
            ''//Add a simple paragraph
            CT.AddElement(New Paragraph("This goes in the margin"))
            ''//Draw the text
            CT.Go()

            ''//For the right margin we'll draw the text manually
            ''//Grab the raw canvas
            Dim cb = writer.DirectContent
            ''//Store the current graphics state so that we can restore it later
            cb.SaveState()
            ''//Flag that we're begining text
            cb.BeginText()
            ''//Set a font and size to draw with
            cb.SetFontAndSize(BaseFont.CreateFont(BaseFont.TIMES_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED), 8)
            ''//Set a color for the text
            cb.SetColorFill(BaseColor.RED)
            ''//Draw the text at a specific x,y coordinate. NOTE: These commands assume do not break text for you automatically
            cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "right margin", document.PageSize.Width - document.RightMargin, yTop, 0)
            ''//Flag that we're doing with our text
            cb.EndText()
            ''//Restore the graphics state to whatever it was before we started messing with it
            cb.RestoreState()

        End Sub
    End Class
End Class