gpt4 book ai didi

javascript - 使用 JavaScript 保存 PDF 文件的第一页

转载 作者:行者123 更新时间:2023-12-03 04:44:58 25 4
gpt4 key购买 nike

我需要提取已上传 PDF 文件的第一页(在 SharePoint Online 中),并使用 JavaScript 将其另存为单独的 PDF 文件
经过一番搜索后我发现 this 。但我无法理解它是如何工作的。请帮忙。

最佳答案

按照评论中的要求 in a previous answer我发布示例代码只是为了获取原始格式的第一页,而不是位图。

这使用 third party REST service可以转换 PDF、合并、分割、水印、安全和 OCR 文件。由于它基于 REST,因此支持多种语言,JavaScript 就是其中之一。

接下来是一个独立的 HTML 页面,不需要您添加任何额外的服务器端逻辑。它允许上传 PDF 文件,将 PDF 分割成单独的页面,然后丢弃除第一页之外的所有页面。使用此服务还有其他方法可以实现相同的目的,但这是我想到的最简单的方法。

You need to create an account获取 API key ,然后您需要将其插入代码中。

下面的相当多的代码涉及 UI 并将生成的 PDF 推送到浏览器。当然,您可以通过删除所有代码来显着缩短它。


<!DOCTYPE html>
<html>
<head>
<title>Muhimbi API - Split action</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">

// ** Specify the API key associated with your subscription.
var api_key = '';

// ** For IE compatibility*
// ** IE does not support 'readAsBinaryString' function for the FileReader object. Create a substitute function using 'readAsArrayBuffer' function.
if (FileReader.prototype.readAsBinaryString === undefined) {
FileReader.prototype.readAsBinaryString = function (file_content) {
var binary_string = "";
var thiswindow = this;
var reader = new FileReader();
reader.onload = function (e) {
var bytes = new Uint8Array(reader.result);
var length = bytes.byteLength;
for (var i = 0; i < length; i++) {
binary_string += String.fromCharCode(bytes[i]);
}
thiswindow.content = binary_string;
$(thiswindow).trigger('onload');
}
reader.readAsArrayBuffer(file_content);
}
}
// ** For IE compatibility*

// ** Create a Blob object from the base64 encoded string.
function CreateBlob(base64string)
{
var file_bytes = atob(base64string);

var byte_numbers = new Array(file_bytes.length);
for (var i = 0; i < file_bytes.length; i++) {
byte_numbers[i] = file_bytes.charCodeAt(i);
}

var byte_array = new Uint8Array(byte_numbers);

var file_blob = new Blob([byte_array], {type: "application/pdf"});

return file_blob;
}

// ** Execute code when DOM is loaded in the browser.
$(document).ready(function ()
{
//** Make sure an api key has been entered.
if(api_key=='')
{
alert('Please update the sample code and enter the API Key that came with your subscription.');
}

// ** Attach a click event to the Convert button.
$('#btnConvert').click(function ()
{
// ** Proceed only when API Key is provided.
if(api_key=='')
return;

try
{
// ** Get the file object from the File control.
var source_file = document.getElementById('file_to_split').files[0];

//** Was a file uploaded?
if (source_file)
{
// ** Get the file name from the uploaded file.
var source_file_name = source_file.name;

var reader = new FileReader();

//** Read the file into base64 encoded string using FileReader object.
reader.onload = function(reader_event)
{
var binary_string;

if (!reader_event) {
// ** For IE.
binary_string = reader.content;
}
else {
// ** For other browsers.
binary_string = reader_event.target.result;
}

// ** Convert binary to base64 encoded string.
var source_file_content = btoa(binary_string);

if(source_file_content)
{
// ** We need to fill out the data for the conversion operation
var input_data = "{";
input_data += '"use_async_pattern": false';
input_data += ', "fail_on_error": false';
input_data += ', "split_parameter": 1';
input_data += ', "file_split_type": "ByNumberOfPages"';
input_data += ', "source_file_name": "' + source_file_name + '"'; // ** Always pass the name of the input file with the correct file extension.
input_data += ', "source_file_content": "' + source_file_content + '"'; // ** Pass the content of the uploaded file, making sure it is base64 encoded.
input_data += '}',

// ** Allow cross domain request
jQuery.support.cors = true;

// ** Make API Call.

$.ajax(
{
type: 'POST',

// ** Set the request header with API key and content type
beforeSend: function(request)
{
request.setRequestHeader("Content-Type", 'application/json');
request.setRequestHeader("api_key", api_key);
},

url: 'https://api.muhimbi.com/api/v1/operations/split_pdf',

data: input_data,

dataType: 'json',

// ** Carry out the conversion
success: function (data)
{
var result_code = "";
var result_details = "";
var processed_file_contents = "";
var base_file_name = "";

// ** Read response values.
$.each(data, function (key, value)
{
if (key == 'result_code')
{
result_code = value;
}
else if (key == 'result_details')
{
result_details = value;
}
else if (key == 'processed_file_contents')
{
processed_file_contents = value;
}
else if (key == 'base_file_name')
{
base_file_name = value;
}
});

// ** Show result code and details.
$("#spnResultCode").text(result_code);
$("#spnResultDetails").text(result_details);

if(result_code=="Success")
{
// ** Get first item in the array. This is the first page in the PDF
var processed_file_content = processed_file_contents[0];

// ** Convert to Blob.
var file_blob = CreateBlob(processed_file_content)

// ** Prompt user to save or open the converted file
if (window.navigator.msSaveBlob) {
// ** For IE.
window.navigator.msSaveOrOpenBlob(file_blob, base_file_name + "." + output_format);
}
else {
// ** For other browsers.
// ** Create temporary hyperlink to download content.
var download_link = window.document.createElement("a");
download_link.href = window.URL.createObjectURL(file_blob, { type: "application/octet-stream" });
download_link.download = base_file_name + ".pdf";
document.body.appendChild(download_link);
download_link.click();
document.body.removeChild(download_link);
}
}
},

error: function (msg, url, line)
{
console.log('error msg = ' + msg + ', url = ' + url + ', line = ' + line);

// ** Show the error
$("#spnResultCode").text("API call error.");
$("#spnResultDetails").text('error msg = ' + msg + ', url = ' + url + ', line = ' + line);
}
});
}
else
{
// ** Show the error
$("#spnResultCode").text("File read error.");
$("#spnResultDetails").text('Could not read file.');
}

};

reader.readAsBinaryString(source_file);
}
else
{
alert('Select file to convert.');
}
}
catch(err)
{
console.log(err.message);

// ** Show exception
$("#spnResultCode").text("Exception occurred.");
$("#spnResultDetails").text(err.message);
}

});

});
</script>

</head>

<body>
<div>
<form id="convert_form">


Select file: <input type="file" id="file_to_split" />

<br /><br />

<button id="btnConvert" type="button">Split PDF</button>

<br /><br />

Result_Code: <span id="spnResultCode"></span>
<br />
Result_Details: <span id="spnResultDetails"></span>

</form>
</div>
</body>

</html>


重要的免责声明,我从事这项服务,所以请认为我有偏见。话虽如此,它效果很好,并且有可能解决您的问题。

关于javascript - 使用 JavaScript 保存 PDF 文件的第一页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42904580/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com