【问题标题】:Using iText 7 and Powershell to write text/lines/boxes to PDF使用 iText 7 和 Powershell 将文本/行/框写入 PDF
【发布时间】:2020-07-06 18:19:31
【问题描述】:

我已经设法使用 PowerShell 和 iText 7 创建了一个空白 PDF。我想在新创建的 PDF 中写入一些文本、行和框,但找不到任何有关如何执行此操作的信息。这是我到目前为止所拥有的,这是我尝试将文本写入创建的 PDF。任何帮助或帮助方向将不胜感激。

[string] $pdfDocuFilename = "C:\test\meow4.pdf"
$pdfWriter = [iText.Kernel.Pdf.PdfWriter]::new($pdfDocuFilename)
$pdf = [iText.Kernel.Pdf.PdfDocument]::new($pdfWriter)
$pdf.AddNewPage()
$Paragraph = [iText.Layout.Element.Paragraph]::new()
[iText.Layout.Element.Text] $PDFText = "Hello World"
$Paragraph.Add($PDFText)
$pdf.Close()

【问题讨论】:

  • 你试过$pdf.add($PDFText)$pdf.add($Paragraph)吗?
  • 我刚刚做了,它们都失败了,并出现此错误“方法调用失败,因为 [iText.Kernel.Pdf.PdfDocument] 不包含名为 'Add' 的方法。”
  • 看起来除了PdfDocument 之外,您还需要创建一个Document。查看本教程riptutorial.com/itext

标签: powershell itext7


【解决方案1】:

我也一直在努力解决这个问题。 然而我还没有完全弄清楚,但我可以设法使用以下代码添加文本。

#import the modules
[System.Reflection.Assembly]::LoadFrom("C:\temp\itext.kernel.dll")
Add-Type -Path "C:\temp\Common.Logging.Core.dll"
Add-Type -Path "C:\temp\Common.Logging.dll"
Add-Type -Path "C:\temp\itext.io.dll"
Add-Type -Path "C:\temp\itext.layout.dll"
Add-Type -Path "C:\temp\BouncyCastle.Crypto.dll"

$pdfname = "C:\temp\test.pdf"

$pdfwriter = [iText.Kernel.Pdf.PdfWriter]::new($pdfname)
$pdf = [iText.Kernel.Pdf.PdfDocument]::new($pdfwriter)
$document = [iText.Layout.Document]::new($pdf)
$paragraph = [iText.Layout.Element.Paragraph]::new($document)
$text = [itext.Layout.Element.Text]::new("Hello World")

$paragraph.add($text)
$document.add($paragraph)

但这给了我一个看起来像这样的 pdf 文件: iText.Layout.DocumentHello World

但是,当我将其更改为添加如下一行的段落时,它可以正常工作。

$document.Add([iText.Layout.Element.Paragraph]::new("Hello World"))

【讨论】:

    【解决方案2】:

    这是一个有效的 Hello World 示例。 注意:iText 包位于源文件位置的文件夹名称“lib”中

    # $PSScriptRoot gets the source file location
    Add-Type -Path "$PSScriptRoot\lib\Common.Logging.Core.dll"
    Add-Type -Path "$PSScriptRoot\lib\Common.Logging.dll"
    Add-Type -Path "$PSScriptRoot\lib\itext.io.dll"
    Add-Type -Path "$PSScriptRoot\lib\itext.kernel.dll"
    Add-Type -Path "$PSScriptRoot\lib\BouncyCastle.Crypto.dll"
    Add-Type -Path "$PSScriptRoot\lib\itext.kernel.dll"
    Add-Type -Path "$PSScriptRoot\lib\itext.layout.dll"
    
    $desc = "$PSScriptRoot\hello_world.pdf"
    $writer = [iText.Kernel.Pdf.PdfWriter]::new($desc)
    $pdf = [iText.Kernel.Pdf.PdfDocument]::new($writer)
    $document = [iText.Layout.Document]::new($pdf)
    $document.Add([iText.Layout.Element.Paragraph]::new("Hello World!"))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-19
      • 2023-04-09
      • 2019-06-30
      • 1970-01-01
      • 2013-04-04
      • 2010-11-16
      • 2014-09-01
      • 2010-12-19
      相关资源
      最近更新 更多