2

我使用 iTextSharp 创建了一个 PDF 文件,它存储在我的系统桌面中,并在我的本地系统中成功打开。现在,如果我将相同的代码上传到服务器,则不会发生错误并且不会创建 PDF 文件。这是我创建和打开 pdf 的部分代码。

PdfWriter.GetInstance(doc, new FileStream(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\Out.pdf", FileMode.Create));

doc.Open();
DataView DView = (DataView)Session["data_value"];
dtData = DView.ToTable();
dr = dtData.Select("fldemp_no='" + Session["EmployeeID"].ToString() + "'");
doc.NewPage();
iTextSharp.text.Image ObjImg = iTextSharp.text.Image.GetInstance(Server.MapPath("~/Bin/Head.png"));
ObjImg.Alignment = iTextSharp.text.Image.ALIGN_CENTER;
ObjImg.ScaleToFit(220f, 150f);
ObjImg.SpacingBefore = 13f;
ObjImg.SpacingAfter = 1f;
doc.Add(ObjImg);

maintable = new PdfPTable(1);
cell = new PdfPCell(new Phrase("Pay Slip for the month of " + dr[0]["fldmonth"].ToString(), fnt1));
cell.HorizontalAlignment = Element.ALIGN_CENTER;
cell.Border = 0;
maintable.AddCell(cell);
doc.Add(maintable);

maintable = new PdfPTable(2);
empdetright = new PdfPTable(2);

empdetleft = new PdfPTable(2);
cell = new PdfPCell(new Phrase("Emp No", fnt1));
cell.Border = 0;
empdetright.AddCell(cell);

cell = new PdfPCell(new Phrase(": " + dr[0]["fldemp_no"].ToString(), fnt1));
cell.Border = 0;
empdetright.AddCell(cell);

cell = new PdfPCell(new Phrase("Emp Name", fnt1));
cell.Border = 0;
empdetright.AddCell(cell);
cell = new PdfPCell(new Phrase(": " + dr[0]["fldempname"].ToString(), fnt1));
cell.Border = 0;
empdetright.AddCell(cell);

doc.Close();
Process.Start(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "/out.pdf"); 
4

1 回答 1

0

在 Web 应用程序中,您需要在响应流中返回 PDF 文档。这是一个简单的例子:

var response = HttpContext.Current.Response;
response.Clear();
response.ContentType = "application/pdf";

MemoryStream mem = new MemoryStream(); // PDF data will be written here
PdfWriter writer = PdfWriter.GetInstance(doc, mem);  // tie a PdfWriter instance to the stream

doc.Open();

// ... Doing the pdf generation

doc.Close();

// write the document data to response stream
writer.Flush();
response.OutputStream.Write(mem.GetBuffer(), 0, mem.GetBuffer().Length);
response.OutputStream.Flush();
response.OutputStream.Close();
response.End();
于 2012-06-27T11:24:30.623 回答