Para recibir archivos PDF del backend, se nos enviarán como un array de bytes. Si se nos envía directamente ese array como cuerpo de la respuesta, podemos especificar desde Axios el tipo de respuesta, así:
return apiRequest({ url, responseType: "arraybuffer" }); |
Una vez recibido, para descargarlo podemos utilizar el código de la siguiente función, pasándole el pdf y el nombre del archivo a descargar:
// Descargar un pdf (arraybuffer)
descargarPdf(pdfArrayBuf, nombre) {
const blob = new Blob([pdfArrayBuf], {
type: 'application/pdf',
});
// IE doesn't allow using a blob object directly as link href
// instead it is necessary to use msSaveOrOpenBlob
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(blob);
return;
}
// For other browsers:
// Create a link pointing to the ObjectURL containing the blob.
const data = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = data;
link.download = nombre;
link.click();
setTimeout(() => {
// For Firefox it is necessary to delay revoking the ObjectURL
window.URL.revokeObjectURL(data);
}, 100);
}, |
Si lo que queremos es abrirlo en otra pestaña del navegador, lo podemos hacer con esta otra función:
abrirPdf() {
const blob = new Blob([this.matriculaPdf], { type: 'application/pdf' });
// IE doesn't allow using a blob object directly as link href
// instead it is necessary to use msSaveOrOpenBlob
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(blob);
return;
}
// For other browsers:
// Create a link pointing to the ObjectURL containing the blob.
const data = window.URL.createObjectURL(blob);
// window.open(data, '_blank');
const link = document.createElement('a');
link.href = data;
link.target = '_blank';
link.click();
setTimeout(() => {
// For Firefox it is necessary to delay revoking the ObjectURL
window.URL.revokeObjectURL(data);
}, 100);
}, |
Hay algunos componentes Vue de visor de pdf disponibles, pero estos son bastante limitados, pues muestran el pdf "a pelo", no proporcionan ningún tipo de interfaz para navegar o ejecutar acciones como guardar el pdf. Por lo tanto, la mejor opción que tenemos es mostrar el pdf en un iframe, de modo que se utilice el visor nativo del navegador:
<iframe :src="pdf" /> |
En la propiedad src podemos pasarle el pdf en base64, precedido por "data:application/pdf;base64,". Si recibimos el pdf a mostrar como array de bytes, podemos transformarlo así:
this.pdf = `data:application/pdf;base64, ${btoa(String.fromCharCode.apply(null, new Uint8Array(arraybuffer)),)}`; |
Siendo la variable arraybuffer el array de bytes del pdf que hemos recibido.