douhe5092 2015-10-02 06:40
浏览 94
已采纳

通过html5中的ajax在网络文件夹中显示pdf

I'm having trouble outputting a pdf to the web. The layout is a select on the left, that has different pdf file names, and when the user chooses one, it is displayed on the right, through an ajax call. My pdfs are in a network folder where I can't use an URL, so what I do is reading it through php

$file = 'C:/Cargos/data.pdf' // trying it out first with filesystem
header('Content-type: application/pdf');
header("Content-Disposition: inline; filename=doc.pdf")
header('Content-Transfer-Encoding: binary');
header('Accept-Ranges: bytes');
readfile($file);

The problem is that the output of this is somewhat garbage, this is the binary raw data of the pdf and I haven't found a way to load it, this is the response from ajax call:

/Creator (Canon iR-ADV C5235 PDF) /CreationDate (D:20150928152404+02'00') /Producer (\376\377\000A\000d\000o\000b\000e\000 \000P\000S\000L\000 \0001\000.\000\ 2\000e\000 \000f\000o\000r\000 \000C\000a\000n\000o\000n\000\000) x� \TU�8~���Lдt2C��W)njH�8�I�2���)���}͌�l�Q�

It goes on and on, I just cut it here.

I have made it work if I move the pdf to one temp folder with a fixed name and reload an iframe always pointing to that URL, but I feel that this is a really bad solution.

Any help on reading this binary input and displaying it? Thanks.

  • 写回答

1条回答 默认 最新

  • douduoting8408 2015-10-02 08:24
    关注

    I think I may have solved it, reading the pdf, then encoding it as a base64:

    $plain = fread(fopen($file,'r'),filesize($file));
    $pdfBase64=base64_encode($plain);
    echo $pdfBase64;
    

    Part of my ajax function, I modify the src attribute and make it read from base64 encoding, data contains the base64 coded pdf:

    dataType: 'text',
    success : function(data) {
    $("#myIframe").attr('src', 'data:application/pdf;base64,'+ data);
    }
    

    Still, not the best approach but it works.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突