2016-03-28 94 views
0

在移动浏览器上生成pdf文件时,我遇到了以下问题:在某些移动浏览器中文件被损坏,但某些文件被下载但未显示文本,它只在文件中显示图像。同时,在桌面浏览器上工作时文件生成得很完美,并且下载时文件内容完美显示。我不知道背后的真实原因,因为我在开发Web应用程序方面是全新的。在移动浏览器上工作时生成pdf文件时出现问题

我使用的代码在下面给出:

Document pdfDoc = new Document(PageSize.A4, 10, 10, 10, 10); 
PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDoc,   Response.OutputStream); 
pdfDoc.Open(); 
string imageUrl = Server.MapPath("~/logo//bcetlogo.jpg"); 
iTextSharp.text.Image ImageLogo = iTextSharp.text.Image.GetInstance(imageUrl); 
ImageLogo.ScaleToFit(80f, 80f); 
pdfDoc.Add(ImageLogo); 
Font f = FontFactory.GetFont("Arial", 15); 
string title = "HelloWorld"; 
Paragraph text1 = new Paragraph(title, f); 
pdfDoc.Add(text1); 
pdfWriter.CloseStream = false; 
pdfWriter.Close(); 
Response.Buffer = true; 
Response.ContentType = "application/octet-stream"; 
Response.AddHeader("Content-Disposition", "attachment;filename=Example.PDF"); 
Response.Cache.SetCacheability(HttpCacheability.NoCache); 
Response.Write(pdfDoc); 
Response.End(); 
+0

亲爱的@AbhinandanKumar,是我的回答的事情吗?你有没有机会尝试提出的解决方案?它对你有帮助吗? –

回答

1

这肯定是错误的:

Response.Write(pdfDoc); 

pdfDoc目的是Document类型的,并且预计Response.Write()字节,而不是一个对象Document。你声称这在某些情况下是行不通的。

您还需要去掉这两行:

pdfWriter.CloseStream = false; 
pdfWriter.Close(); 

这一行替换它们:

pdfDoc.Close(); 

了解更多关于这里的PDF创建过程中的5个步骤:Getting started。你从哪里得到你的代码?你能保证永远不再看这个文档吗?始终使用official web site

当您完成pdfDoc.Close()时,PDF已完成。收听Document的所有DocListener实例都关闭。在您的情况下,侦听pdfDoc的实例DocListener是您不知道的PdfDocument实例,因为它仅在内部使用。关闭这个PdfDocument实例很重要,因为在那个close()操作中,大量内容被刷新。您可以通过关闭pdfWriter而不是pdfDoc来跳过此步骤。

您还保持内容流打开。这是一个坏主意。内容流应该关闭。直接使用Response.OutputStream时存在一些已知问题。这是更好地使用MemoryStream像答案是做这样一个问题:iTextSharp is producing a corrupt PDF with Response

如果你研究这个答案很好,你会看到这一点:

byte[] bytes = memoryStream.ToArray(); 
Response.Clear(); 
Response.ContentType = "application/pdf"; 
Response.AddHeader("Content-Disposition", "attachment;filename=ControleDePonto.pdf"); 
Response.Buffer = true; 
Response.Cache.SetCacheability(HttpCacheability.NoCache); 
Response.BinaryWrite(bytes); 
Response.End(); 

正如你可以看到你所需要的BinaryWrite()方法该方法预计byte[]。除了代码中的许多其他错误,您的主要错误是您将Document对象传递给Write()方法。

相关问题