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 PointNet++的onnx模型只能使用一次
  • ¥20 西南科技大学数字信号处理
  • ¥15 有两个非常“自以为是”烦人的问题急期待大家解决!
  • ¥30 STM32 INMP441无法读取数据
  • ¥15 R语言绘制密度图,一个密度曲线内fill不同颜色如何实现
  • ¥100 求汇川机器人IRCB300控制器和示教器同版本升级固件文件升级包
  • ¥15 用visualstudio2022创建vue项目后无法启动
  • ¥15 x趋于0时tanx-sinx极限可以拆开算吗
  • ¥500 把面具戴到人脸上,请大家贡献智慧,别用大模型回答,大模型的答案没啥用
  • ¥15 任意一个散点图自己下载其js脚本文件并做成独立的案例页面,不要作在线的,要离线状态。