一周前刚开始使用 iTextSharp - 你会认为有些事情是显而易见的,但显然不是。
我想在使用 PDFWriter 添加动态内容之前创建一个 PDF 报告结构(即线条、图像和静态文本)。此报告模板将用于三种类型的报告。
这意味着,我构建了页面,然后我想回到第 1 页并添加一些新内容,然后转到第 2 页并添加更多内容,然后转到第 3 页,依此类推。我会提前确定我需要的页数来构建模板,然后添加额外的内容。
创建页面没有问题。使用 GotoLocalPage 返回第 1 页(或我可能想要调用的任何页面)没有问题。但是我想添加的所有新的直接内容都在最后一页结束。
如何将光标或插入点(由于缺乏知识)移动到任何前一页并开始添加新内容?
我尝试过大纲、书签、锚点,但它们似乎都在向页面添加文本 - 是诸如不可见的锚点之类的东西(即,使用空字符串?)
我不想关闭文档并重新打开以添加其他内容 - 应该有一种方法可以移动到文档的任何给定部分并添加其他内容。
我添加了一些代码作为参考 - 代码是 VB.net,但我在解释 Java 或 C# 时没有任何问题 - 抱歉,我无法添加 StackFlow 不允许我添加的图像,因为我是新手!
Private Sub BuildPDFDocument(ByVal DocType As String, ByVal OutFileName As String, ByVal Pages As Integer)
OutFile = New Document(PageSize.LETTER, 0, 0, 0, 0)
OutFile.SetPageSize(PageSize.LETTER.Rotate())
Try
Using Writer = PdfWriter.GetInstance(OutFile, New FileStream(WorkingOutputFolder & OutFileName, FileMode.Create))
OutFile.Open()
'-------------------------------------------------------------------------------------------------------------------
ContentByte = Writer.DirectContent
For i = 1 To Pages
If i > 1 Then OutFile.NewPage()
AddTemplateImages()
AddTemplateLines()
AddTemplateText(DocType, i, Pages)
AddColumnText()
AddBarcodeEAN()
AddBarcode39()
AddBarcodeQR()
'THIS WORKS BUT I DO NOT WANT TO ADD DYNAMIC CONTENT HERE
'I WANT TO BUILD TEMPLATE FIRST AND THEN GO BACK TO PAGE ONE AND ADD MORE CONTENT
'AddDynamicContent(i)
Next
'-------------------------------------------------------------------------------------------------------------------
Dim Action As PdfAction
For i = 1 To Pages
'Action = PdfAction.GotoLocalPage(i, New PdfDestination(PdfDestination.FIT), Writer)
Action = PdfAction.GotoLocalPage(i, New PdfDestination(PdfDestination.XYZ, -1, 10000, 0), Writer)
Writer.SetOpenAction(Action)
'HERE IS THE PROBLEM - I WANT TO GO TO A SPECIFIC PAGE THEN ADD SOME CONTENT
'WHEN DONE MOVE TO THE NEXT PAGE ADD SOME MORE CONTENT AND SO AND SO FORTH
'BUT ALL THE CONTENT ENDS UP ON THE LAST PAGE REGARDLESS OF ME MOVING FROM PAGE TO PAGE
'HOW DO I MOVE THE CURSOR or INSERTION POINT TO A LOCAL PAGE I HAVE CALLED
'AND ADD NEW Chunks/Phrases/Paragraphs TO THAT PAGE
AddDynamicContent(i)
Next
'GO BACK TO PAGE 1
Action = PdfAction.GotoLocalPage(1, New PdfDestination(PdfDestination.FIT), Writer)
Writer.SetOpenAction(Action)
'-------------------------------------------------------------------------------------------------------------------
OutFile.Close()
End Using
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub AddDynamicContent(ByVal PageNumber As Integer)
'JUST TESTING RIGHT NOW
ContentByte.BeginText()
'------------------------------------------------------------------------------
ContentByte.SetFontAndSize(FontByName("TimesNewRoman"), 8)
ContentByte.SetTextMatrix(58.0F, 333.0F)
ContentByte.ShowText("DYNAMIC CONTENT ON PAGE " & PageNumber.ToString)
'------------------------------------------------------------------------------
ContentByte.EndText()
End Sub