c# - 该进程无法访问该文件,因为它正被另一个进程使用 (iTextSharp c#)

标签 c# asp.net itext

我有一个下载 PDF 处理程序:

    // Build the PDF
    Manual.Functions.createEntireManual(ThisDownload.FileLocation);

    // Download file
    context.Response.Clear();
    context.Response.Buffer = false;
    context.Response.ContentType = "application/pdf";
    context.Response.AddHeader("Content-disposition", "attachment; filename=Construct2-Manual-Full.pdf");        
    context.Response.AddHeader("Content-Length", FileSize.ToString());
    context.Response.TransmitFile(Settings.ManualBinLocation + ThisDownload.ID + ".pdf");
    context.Response.Close();

创建手动函数如下所示:

public static void createEntireManual(string PDFPath)
{
    iTextSharp.text.Document d = new iTextSharp.text.Document();
    d.Open();

    using (iTextSharp.text.pdf.PdfWriter p = iTextSharp.text.pdf.PdfWriter.GetInstance(d, new FileStream(PDFPath, FileMode.Create)))
    {
        d.Add(new Paragraph("Hello world!"));
    }            
}

这会引发错误:

Exception Details: System.IO.IOException: The process cannot access the file 'C:\inetpub\wwwroot\manuals\26.pdf' because it is being used by another process.

很好,所以我在我的函数中添加了 d.Close():

        d.Add(new Paragraph("Hello world!"));            
    }    
    d.Close();        
}

但这会抛出:

Exception Details: System.Exception: The document is not open.

d.Close() 行。我尝试将新的 Document 对象添加为 using 语句,但它不喜欢这样,抛出无意义的错误:

Exception Details: System.Exception: The document is not open.

关于使用右括号。

有没有对 iTextSharp 更有经验的人帮助我?

最佳答案

您是否需要将 PDF 保存到文件系统?否则,直接使用 HttpResponse 对象的 OutputStream 会容易得多。这是一个简单的例子:

<%@ WebHandler Language="C#" Class="handlerExample" %>
using System;
using System.Web;
using iTextSharp.text;  
using iTextSharp.text.pdf;

public class handlerExample : IHttpHandler {
  public void ProcessRequest (HttpContext context) {
    HttpResponse Response = context.Response;
    Response.ContentType = "application/pdf";
    Response.AddHeader(
      "Content-disposition", 
      "attachment; filename=Construct2-Manual-Full.pdf"
    );  
    using (Document document = new Document()) {
      PdfWriter.GetInstance(
        document, Response.OutputStream
      );
      document.Open();
      document.Add(new Paragraph("Hello World!"));
    }
  }
  public bool IsReusable { get { return false; } }
}

所以说你不应该使用 using 语句是不正确的。上面的例子是简化的,但可以很容易地扩展;根据您在上面命名方法的方式,也许您正在从许多不同的较小 PDF 文档构建 PDF 手册?

关于c# - 该进程无法访问该文件,因为它正被另一个进程使用 (iTextSharp c#),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8316772/

相关文章:

c# - Rhino Mocks 示例如何模拟属性

android - 支持 native 移动应用程序中的 ASP.Net Forms 身份验证

asp.net - asp.net core mvc中Model和ViewModel有什么区别?

c# - 使用 iTextSharp 锁定 PDF 以防止编辑

c# - 更改 itextsharp 的字体大小

c# - 划分两个 TimeSpan 对象的最佳方法是什么?

c# - 在 C# 中检查一个字符串是否与多个子字符串组合

c# - Java 保存和恢复框架位置、大小和状态

asp.net - 使用 SignalR 和 Azure 的实时通知系统

java.lang.NoSuchMethodError : org. apache.poi.util.POILogger.log(ILjava/lang/Object;Ljava/lang/Throwable;)V