我有一个下载 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/