首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >PDFObject在浏览器中显示不正确

PDFObject在浏览器中显示不正确
EN

Stack Overflow用户
提问于 2019-12-11 15:24:00
回答 2查看 492关注 0票数 1

我正在尝试使用PDFObject渲染一个嵌入的pdf文件。在后端,我发送的pdf如下

代码语言:javascript
复制
fs.readFile(uploadFileFd, function (err,data){
    res.contentType("application/pdf");
    res.send(data);
 });

在那之后,我在前面得到了如下响应

代码语言:javascript
复制
$.get("/loadDocument",function(data){
    PDFObject.embed(data,"#test");
  });

我得到了下面的结果image with the render in the browser of the pdf

你知道怎么解决吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-03-01 23:09:00

我发现问题出在pdf文件的编码上,所以我在后台使用‘base64 -base64’将文件编码为流:

代码语言:javascript
复制
      var readStream = fs.createReadStream(uploadFileFd);

      // This will wait until we know the readable stream is actually valid before piping
      readStream.on('open', function () {
        // This just pipes the read stream to the response object (which goes to the client)
        readStream.pipe(new Base64Encode()).pipe(res);
      });
      // This catches any errors that happen while creating the readable stream (usually invalid names)
      readStream.on('error', function(err) {
        res.end(err);
      });

之后,我使用一个embed标签来显示pdf:

代码语言:javascript
复制
var newElement = "<embed src=data:application/pdf;base64,"+data+" id='pdf' width='100%' height='1200'>";
票数 1
EN

Stack Overflow用户

发布于 2019-12-11 17:45:28

它似乎是以二进制格式出现的,所以你需要再次将其转换为pdf以便在浏览器上呈现。

代码语言:javascript
复制
var request = new XMLHttpRequest();
request.open("GET", "/path/to/pdf", true); 
request.responseType = "blob";
request.onload = function (e) {
    if (this.status === 200) {
        // `blob` response
        console.log(this.response);
        // create `objectURL` of `this.response` : `.pdf` as `Blob`
        var file = window.URL.createObjectURL(this.response);
        var a = document.createElement("a");
        a.href = file;
        a.download = this.response.name || "detailPDF";
        document.body.appendChild(a);
        a.click();
        // remove `a` following `Save As` dialog, 
        // `window` regains `focus`
        window.onfocus = function () {                     
          document.body.removeChild(a)
        }
    };
};
request.send();

请尝试上面的。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59280673

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档