我正在使用mPDF库从HTML页面生成PDF文件。它在firefox中工作得很好,但它不是在chrome浏览器中显示PDF文件。
我在chrome中生成PDF时出现以下错误。
以下是我使用mPDF生成PDF的代码
ob_clean();
header('Content-type: application/pdf');
header('Content-Disposition: inline; filename="' . $yourFileName . '"');
header('Content-Transfer-Encoding: binary');
header('Accept-Ranges: bytes');
$mpdf = new PDF( 'c','A4','','',15, 15,10,14,0,0);
$mpdf->useOnlyCoreFonts = false;
$mpdf->SetDisplayMode('real');
$mpdf->list_indent_first_level = 0; // 1 or 0 - whether to indent the first level of a list
$stylesheet = file_get_contents(APPPATH . 'third_party/mpdf/style.css');
$mpdf->WriteHTML($stylesheet,1);
$mpdf->WriteHTML($html);
$mpdf->Output();
这是人们在较旧版本的Chrome上遇到的问题。如果您仍然看到此问题,请执行以下操作
在Google Chrome中,您有2个选项可用于查看PDF文件。您可以使用Chrome pdf查看器(默认),也可以使用Adobe Reader
你能检查chrome:// plugins(在地址栏中输入)吗?只需启用它即可切换到其他PDF查看器(Chrome / Adobe)!
这可能是生成的pdf的问题。如果它适用于Firefox,请下载该文件并尝试打开它。如果你电脑中的pdf查看器输出损坏的pdf,那么你可能需要调整你的代码。我面临同样的问题。由于pdf损坏,Chrome无法打开它。
希望我的回答能让你进入调试之旅。干杯。 :d
当您使用html到PDF库(如mPDF)时,也会发生这种情况,并且在发送文件之前,您会以某种方式将HTML发送到浏览器。许多读者在阅读PDF标记之前忽略了HTML - Chrome没有。
例如,在PHP中,在将数据发送到mPDF之前清除输出缓冲区:ob_clean()
。
对于使用MemoryStream打开的浏览器pdf中的Chrome,以下代码块在C#中为我工作:
MemoryStream ms;
ms = new MemoryStream(result.ResponseData[0].Report);
HttpContext context = HttpContext.Current;
HttpContext context = HttpContext.Current;
context.Response.Clear();
context.Response.ClearContent();
context.Response.ClearHeaders();
context.Response.ContentType = "application/pdf";
context.Response.AddHeader("Content-Disposition", "inline;filename=" + Guid.NewGuid().ToString() + "." + _exportType);
context.Response.AddHeader("Content-Length", ms.Length.ToString());
context.Response.BinaryWrite(ms.ToArray());
context.Response.Flush();
context.Response.Close();
context.Response.End();
在Asp.net Core 2.10中,这对我来说很好。
MemoryStream ms1;
ms1 = new MemoryStream(res);
HttpContext context = _httpContextAccessor.HttpContext;
context.Response.Clear();
context.Response.ContentType = "application/pdf";
context.Response.Headers.Add("Content-Disposition", "inline;filename=" + Guid.NewGuid().ToString() + "." + "pdf");
context.Response.Headers.Add("Content-Length", ms1.Length.ToString());
context.Response.Body.Write(ms1.ToArray());
context.Response.Body.Flush();
context.Response.Body.Close();
希望这是有帮助的。
您可能会发现Chrome的名称标题有问题:Content-Type
值:charset=utf-8
。删除响应标头值为我修复了它。 (原post)