如何使用javascript + HTML5了解PDF版本 [英] How to know the PDF Version using javascript + HTML5

查看:127
本文介绍了如何使用javascript + HTML5了解PDF版本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用客户端可用选项(javascript,HTML5或其他)检查PDF的版本,因为我必须验证PDF版本必须是1.3并且如果PDF版本是1.3而不是仅将其上载到服务器中。

I want to check the version of the PDF using client side available options (javascript, HTML5 or others) as i have to validate that PDF version must be 1.3 and if the PDF version is 1.3 than only will upload it in the server.

我知道有各种服务器端选项可用于识别pdf版本,但我希望客户端可用选项,因此用户无需重新上传整个文件,如果它不是版本1.3

I know that there are various server side option available for identifying the pdf version but i want the client side available option so user don't need to re-upload the entire file again if it's not Version 1.3

提前致谢。

推荐答案

您必须使用 FileReader API

首先创建一个FileReader并注册 onload 处理程序。

Begin by creating a FileReader and registering an onload handler.

由于PDF的前几个字节应该是纯ASCII,我们可以将它们作为文本读取,看起来应该像%PDF-1.3 (其中1.3是如果我们得到字节5到7(是的)我知道它说 file.slice(5,8)我没有写规范;))。

As a the first few bytes of a PDF should be plain ASCII we can read them as text and should look something like %PDF-1.3 (where 1.3 is the version) so if we get bytes 5 to 7 (Yes I know it says file.slice(5, 8) I didn't write the spec ;)).

应该相当直接地进行形式验证。 留给读者练习

Should be fairly straight forward to drop in to form validation. Left as an exercise for the reader

CAVEAT

这是一个简单的例子,适用于xx版本但无法正确读取版本x.xx。

This is a simple example and will work for x.x versions but would fail to read versions x.xx properly without modification.

const pdfUpload = document.getElementById('pdfUpload');
const pdfVersion = document.getElementById('pdfVersion');

// wait for input to be "changed"
pdfUpload.addEventListener('change', (e) => {

  // grab the selected file
  let [file] = e.target.files;

  if (!file) return;

  // use a FileReader
  let reader = new FileReader();
  reader.onload = (e) => {
  
    // read the content
    let versionString = e.target.result;
    pdfVersion.innerText = versionString;
  };

  // PDF file should start something like '%PDF-1.3'
  // grab only the bits we need
  reader.readAsText(file.slice(5, 8));
})

<input type="file" id="pdfUpload" />
<div>PDF Version: <span id="pdfVersion"></span></div>

这篇关于如何使用javascript + HTML5了解PDF版本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆