Javascript 使用javascript在新窗口中打开PDF字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2805330/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:01:01  来源:igfitidea点击:

Opening PDF String in new window with javascript

javascriptpdf

提问by DaveC

I have a formatted PDF string that looks like

我有一个格式化的 PDF 字符串,看起来像

%PDF-1.73 0 obj<<< /Type /Group /S /Transparency /CS /DeviceRGB >> /Resources 2 0 R/Contents 4 0 R>> endobj4 0 obj<> streamx??R=o?0??+??=|vL?R???l?-???,???Ge?JK????{???Y5?????Z?k?vf?a??`G????Asf?z????`%??aI#?!;?t???GD?!???<?????B?b??

...

00000 n 0000000703 00000 n 0000000820 00000 n 0000000926 00000 n 0000001206 00000 n 0000001649 00000 n trailer << /Size 11 /Root 10 0 R /Info 9 0 R >>startxref2015%%EOF

I am trying to open up this string in a new window as a PDF file. Whenever I use window.open() and write the string to the new tab it thinks that the text should be the contents of an HTML document. I want it to recognize that this is a PDF file.

我试图在新窗口中打开这个字符串作为 PDF 文件。每当我使用 window.open() 并将字符串写入新选项卡时,它认为文本应该是 HTML 文档的内容。我希望它能够识别出这是一个 PDF 文件。

Any help is much appreciated

任何帮助深表感谢

回答by Noby Fujioka

Just for information, the below

仅供参考,以下

window.open("data:application/pdf," + encodeURI(pdfString)); 

does not work anymore in Chrome. Yesterday, I came across with the same issue and tried this solution, but did not work (it is 'Not allowed to navigate top frame to data URL'). You cannot open the data URL directly in a new window anymore. But, you can wrap it in iframe and make it open in a new window like below. =)

在 Chrome 中不再起作用。昨天,我遇到了同样的问题并尝试了这个解决方案,但没有奏效(“不允许将顶部框架导航到数据 URL”)。您不能再直接在新窗口中打开数据 URL。但是,您可以将其包装在 iframe 中并在如下所示的新窗口中打开它。=)

let pdfWindow = window.open("")
pdfWindow.document.write(
    "<iframe width='100%' height='100%' src='data:application/pdf;base64, " +
    encodeURI(yourDocumentBase64VarHere) + "'></iframe>"
)

回答by Morgan ARR Allen

You might want to explore using the data URI. It would look something like.

您可能希望使用数据 URI 进行探索。它看起来像。

window.open("data:application/pdf," + escape(pdfString));

I wasn't immediately able to get this to work, possible because formating of the binary string provided. I also usually use base64 encoded data when using the data URI. If you are able to pass the content from the backend encoded you can use..

我无法立即使其工作,这可能是因为提供了二进制字符串的格式。在使用数据 URI 时,我通常也使用 base64 编码的数据。如果您能够从编码的后端传递内容,您可以使用..

window.open("data:application/pdf;base64, " + base64EncodedPDF);

Hopefully this is the right direction for what you need. Also note this will not work at all in IE6/7 because they do not support Data URIs.

希望这是您需要的正确方向。另请注意,这在 IE6/7 中根本不起作用,因为它们不支持数据 URI。

回答by Ramprabhu Kaliaperumal

window.open("data:application/pdf," + escape(pdfString)); 

The above one pasting the encoded content in URL. That makes restriction of the content length in URL and hence PDF file loading failed (because of incomplete content).

上面的将编码的内容粘贴到 URL 中。这限制了 URL 中的内容长度,因此 PDF 文件加载失败(因为内容不完整)。

回答by Felipe Bejarano

This one worked for me.

这个对我有用。

window.open("data:application/octet-stream;charset=utf-16le;base64,"+data64);

This one worked too

这个也有效

 let a = document.createElement("a");
 a.href = "data:application/octet-stream;base64,"+data64;
 a.download = "documentName.pdf"
 a.click();

回答by Chris Cashwell

I realize this is a pretty old question, but I had the same thing come up today and came up with the following solution:

我意识到这是一个非常古老的问题,但我今天遇到了同样的问题,并提出了以下解决方案:

doSomethingToRequestData().then(function(downloadedFile) {
  // create a download anchor tag
  var downloadLink      = document.createElement('a');
  downloadLink.target   = '_blank';
  downloadLink.download = 'name_to_give_saved_file.pdf';

  // convert downloaded data to a Blob
  var blob = new Blob([downloadedFile.data], { type: 'application/pdf' });

  // create an object URL from the Blob
  var URL = window.URL || window.webkitURL;
  var downloadUrl = URL.createObjectURL(blob);

  // set object URL as the anchor's href
  downloadLink.href = downloadUrl;

  // append the anchor to document body
  document.body.appendChild(downloadLink);

  // fire a click event on the anchor
  downloadLink.click();

  // cleanup: remove element and revoke object URL
  document.body.removeChild(downloadLink);
  URL.revokeObjectURL(downloadUrl);
});

回答by Himanshu Chawla

var byteCharacters = atob(response.data);
var byteNumbers = new Array(byteCharacters.length);
for (var i = 0; i < byteCharacters.length; i++) {
  byteNumbers[i] = byteCharacters.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
var file = new Blob([byteArray], { type: 'application/pdf;base64' });
var fileURL = URL.createObjectURL(file);
window.open(fileURL);

You return a base64 string from the API or another source. You can also download it.

您从 API 或其他来源返回一个 base64 字符串。您也可以下载它。

回答by Hasibul

I just want to add with @Noby Fujioka's response, Edge will not support following

我只想添加@Noby Fujioka 的回复,Edge 将不支持关注

window.open("data:application/pdf," + encodeURI(pdfString));

For Edge we need to convert it to blob and this is something like following

对于 Edge,我们需要将其转换为 blob,这类似于以下内容

//If Browser is Edge
            if (window.navigator && window.navigator.msSaveOrOpenBlob) {
                var byteCharacters = atob(<Your_base64_Report Data>);
                var byteNumbers = new Array(byteCharacters.length);
                for (var i = 0; i < byteCharacters.length; i++) {
                    byteNumbers[i] = byteCharacters.charCodeAt(i);
                }
                var byteArray = new Uint8Array(byteNumbers);
                var blob = new Blob([byteArray], {
                    type: 'application/pdf'
                });
                window.navigator.msSaveOrOpenBlob(blob, "myreport.pdf");
            } else {
                var pdfWindow = window.open("", '_blank');
                pdfWindow.document.write("<iframe width='100%' style='margin: -8px;border: none;' height='100%' src='data:application/pdf;base64, " + encodeURI(<Your_base64_Report Data>) + "'></iframe>");
            }

回答by EaziLuizi

Based off other old answers:

基于其他旧答案:

escape()function is now deprecated,

escape()功能现已弃用,

Use encodeURI()or encodeURIComponent()instead.

使用encodeURI()encodeURIComponent()代替。

Example that worked in my situation:

在我的情况下工作的示例:

window.open("data:application/pdf," + encodeURI(pdfString)); 

Happy Coding!

快乐编码!

回答by Dan Ross

I had this problem working with a FedEx shipment request. I perform the request with AJAX. The response includes tracking #, cost, as well as pdf string containing the shipping label.

我在处理 FedEx 货件请求时遇到了这个问题。我使用 AJAX 执行请求。响应包括跟踪编号、成本以及包含运输标签的 pdf 字符串。

Here's what I did:

这是我所做的:

Add a form:

添加表格:

<form id='getlabel' name='getlabel' action='getlabel.php' method='post' target='_blank'>
<input type='hidden' id='pdf' name='pdf'>
</form>

Use javascript to populate the hidden field's value with the pdf string and post the form.

使用 javascript 用 pdf 字符串填充隐藏字段的值并发布表单。

Where getlabel.php:

哪里getlabel.php:

<?
header('Content-Type: application/pdf');
header('Content-Length: '.strlen($_POST["pdf"]));
header('Content-Disposition: inline;');
header('Cache-Control: private, max-age=0, must-revalidate');
header('Pragma: public');
print $_POST["pdf"];
?>

回答by Joe

An updated version of answer by @Noby Fujioka:

@Noby Fujioka的更新版本答案:

function showPdfInNewTab(base64Data, fileName) {  
  let pdfWindow = window.open("");
  pdfWindow.document.write("<html<head><title>"+fileName+"</title><style>body{margin: 0px;}iframe{border-width: 0px;}</style></head>");
  pdfWindow.document.write("<body><embed width='100%' height='100%' src='data:application/pdf;base64, " + encodeURI(base64Data)+"#toolbar=0&navpanes=0&scrollbar=0'></embed></body></html>");
}