【问题标题】:Save 1st page of a PDF file using JavaScript使用 JavaScript 保存 PDF 文件的第一页
【发布时间】:2017-03-20 13:15:15
【问题描述】:

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

【问题讨论】:

  • 您是说要在 SharePoint 服务器上进行提取还是要在客户端进行提取?
  • 我想在客户端使用javascript提取它
  • 不知道为什么这一切都被否决了,所以投了赞成票。虽然这是一个编程问题,但您可能想尝试 sharepoint.stackexchange.com 来解决 SharePoint 特定问题。

标签: javascript pdf sharepoint pdf-generation


【解决方案1】:

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

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

接下来是一个独立的 HTML 页面,您不需要任何额外的服务器端逻辑。它允许上传 PDF 文件,将 PDF 拆分为单独的页面并丢弃除第一个页面之外的所有页面。使用此服务还有其他方法可以达到同样的效果,但这是我想到的最简单的方法。

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

下面的很多代码处理 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>


大胖免责声明,我从事这项服务,所以认为我有偏见。话虽如此,它运作良好,可能会解决您的问题。

【讨论】:

    【解决方案2】:

    终于找到了解决办法。
    首先使用PDF.JS将上传的PDF转换为图像,在示例代码中进行了一些自定义。
    然后使用jsPDF将第一页图像保存为PDF。

    自定义下载代码,

    $("#download-image").on('click', function() {
    
            var imgData = __CANVAS.toDataURL();
            var doc = new jsPDF();
            doc.addImage(imgData, 0, 0, 210, 300);
            doc.save('page1.pdf');
    });
    

    【讨论】:

    • 虽然这可能适用于您的特定情况,但这不会将您的 PDF 的第一页变成您无法选择文本的位图(并且您的搜索索引器无法找到内容)?如果您需要将第一页完全提取为原始页面,请告诉我。
    • @Muhimbi 是的,您对 PDF 到位图的转换是正确的。这种方法适用于这种特殊情况。请告诉我如何使用 javascript 正确提取 PDF 的第一页
    • 这正是我所需要的。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多