我有一个下载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更有经验的人帮助我吗?
答案 0 :(得分:2)
您需要将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手册?
答案 1 :(得分:0)
想出来,你不应该对using
或Document
对象使用PDFWriter
。此代码有效:
/// <summary>
/// Saves the entire manual as PDF
/// </summary>
public static void createEntireManual(string PDFPath)
{
Document d = new Document();
PdfWriter.GetInstance(d, new FileStream(PDFPath, FileMode.Create));
d.Open();
d.SetPageSize(iTextSharp.text.PageSize.A4);
Image Cover = Image.GetInstance(Settings.ManualBinLocation + "cover.png");
Cover.SetAbsolutePosition(0, 0);
d.Add(Cover);
d.Close();
}