No puedo abrir un PDF en una pestaña en un navegador desde un enlace html.
<a href="https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf" target="_blank">PDF</a>Problema:
Pero, si abro el enlace directamente en el navegador ( https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf ), se abrirá en el navegador sin ningún problema. .
¿Cómo resolver esto?
Puede evitarlo con un script de proxy (en el mismo dominio):
Guarde el código a continuación como test.php e inicie el servidor con php -S localhost:1234 test.php . Vaya a http://localhost:1234 .
if(isset($_GET['url']) && strpos($_GET['url'],"http") > -1) { header('Content-type: application/pdf'); echo file_get_contents($_GET['url']); exit; } ?> <a href="?url=https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf" target="_blank">PDF</a>Con este código puedes descargar el pdf a través de un proxy (api.allorigins.win) lo que evita problemas con la política del mismo origen.
Después de eso, el pdf se guarda con window.URL.createObjectURL y se abre en una nueva ventana.
<script> function loadPdf(url) { var req = new XMLHttpRequest(); req.open("GET", "https://api.allorigins.win/raw?url=" + encodeURIComponent(url), true); req.responseType = "blob"; req.onreadystatechange = function () { if (req.readyState === 4 && req.status === 200){ var blob=new Blob([req.response], {type: 'application/pdf'}); var link=document.createElement('a'); link.target = "_blank"; link.href=window.URL.createObjectURL(blob); link.click(); } }; req.send(); } </script> <a href="javascript:loadPdf('https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf');">PDF</a>