在 Vue 项目中首先通过 npm 安装 PDFObject 插件。
npm install pdfobject
然后通过 import PDFObject from 'pdfobject'; 将 PDFObject 导入到页面。下面是一个使用例子。
<template>
<div>
<div ref="myContainer"></div>
</div>
</template>
<script>
import PDFObject from 'pdfobject';
export default {
mounted() {
this.embedPDF();
},
methods: {
embedPDF() {
const options = {
width: "100%",
height: "500px"
};
PDFObject.embed("myfile.pdf", this.$refs.myContainer, options);
//PDFObject.embed("https://pdfobject.com/pdf/sample-3pp.pdf", "#myContainer",
{ title: "PDF version of your banking statement" });
}
}
}
</script>
不安装包也可以直接引用 PDFObject 的源码PDFObject/pdfobject.js at master · pipwerks/PDFObject · GitHub
引用import PDFObject from './index';
后通过PDFObject
.embed 调用
/**
* PDFObject v2.3.0
* https://github.com/pipwerks/PDFObject
* @license
* Copyright (c) 2008-2024 Philip Hutchison
* @modifiedBy KonghaYao 更改为 ESM 导出
* MIT-style license: http://pipwerks.mit-license.org/
* UMD module pattern from https://github.com/umdjs/umd/blob/master/templates/returnExports.js
*/
'use strict';
//PDFObject is designed for client-side (browsers), not server-side (node)
//Will choke on undefined navigator and window vars when run on server
//Return boolean false and exit function when running server-side
export let support = true;
if (typeof window === 'undefined' || window.navigator === undefined || window.navigator.userAgent === undefined) {
support = false;
}
const pdfobjectversion = '2.3.0';
const win = window;
const nav = win.navigator;
const ua = nav.userAgent;
let suppressConsole = false;
//Fallback validation when navigator.pdfViewerEnabled is not supported
const isModernBrowser = function () {
/*
userAgent sniffing is not the ideal path, but most browsers revoked the ability to check navigator.mimeTypes
for security purposes. As of 2023, browsers have begun implementing navigator.pdfViewerEnabled, but older versions
do not have navigator.pdfViewerEnabled or the ability to check navigator.mimeTypes. We're left with basic browser
sniffing and assumptions of PDF support based on browser vendor.
*/
//Chromium has provided native PDF support since 2011.
//Most modern browsers use Chromium under the hood: Google Chrome, Microsoft Edge, Opera, Brave, Vivaldi, Arc, and more.
//Chromium uses the PDFium rendering engine, which is based on Foxit's PDF rendering engine.
//Note that MS Edge opts to use a different PDF rendering engine. As of 2024, Edge uses a version of Adobe's Reader
const isChromium = win.chrome !== undefined;
//Safari on macOS has provided native PDF support since 2009.
//This cod