我有以下代码可以打开 PDF 并添加一些文本和图像。有一次,我打开了第二个 PDF,将其包装在图像中并将其添加到 PDF 中。操作成功完成后,我想删除第二个 PDF(我包裹在图像中的那个)。问题是文件现在被锁定,直到我重置我的 ASP.NET 应用程序。
在 GetImageFromPdf 方法中,您可以看到我正在创建第二个 PdfReader 实例。问题是,如果我关闭这个阅读器,我的 Create 方法中的阅读器也会关闭!难道我做错了什么?还有其他方法可以实现我的目标吗?
以下是相关代码:
public void Create(string outputFilePath, bool preview = false)
{
using (PdfReader reader = new PdfReader(FilePath))
{
using (PdfStamper stamper = new PdfStamper(reader, new FileStream(outputFilePath, FileMode.Create)))
{
PdfContentByte canvas = stamper.GetOverContent(1);
...
AddMap(canvas, stamper);
}
}
}
...
private void AddMap(PdfContentByte Canvas, PdfStamper stamper)
{
Image ImageWrapper = GetImageFromPdf(stamper.Writer, _MapFilePath);
//set the position and scale the image
ImageWrapper.ScaleAbsolute(152.5f, 152.5f);
ImageWrapper.SetAbsolutePosition(58.5f, 197.5f);
Canvas.AddImage(ImageWrapper);
}
...
public Image GetImageFromPdf(PdfWriter Writer, string MapFilePath)
{
//since vector images are not supported natively by iTextSharp
//we have saved the location maps as PDF (originally in eps format)
//we use GetImportedPage to import the file, and wrap it in an Image object so we can scale it
//If I close this reader, the reader in the Create method is closed as well
PdfReader reader = new PdfReader(MapFilePath);
PdfImportedPage ImportedPage = Writer.GetImportedPage(reader, 1);
return Image.GetInstance(ImportedPage);
}