在 Javascript 中将 PDF 转换为 Base64 编码的字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13538832/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 12:18:48  来源:igfitidea点击:

Convert PDF to a Base64-encoded string in Javascript

javascripthtmlpdfcanvasbase64

提问by onuryilmaz

I need to encode a PDF file to Base64 with Javascript. I can create Base64-encoded jpeg or png images in Javascript, but I could not find any way or sample code to create a Base64-encoded string from a PDF file.

我需要使用 Javascript 将 PDF 文件编码为 Base64。我可以在 Javascript 中创建 Base64 编码的 jpeg 或 png 图像,但是我找不到任何方法或示例代码来从 PDF 文件创建 Base64 编码的字符串。

Is it there any solution using a HTML5 canvas?

有没有使用 HTML5 画布的解决方案?

Thanks.

谢谢。

回答by Mohit Singh

Try this :-

尝试这个 :-

<input id="inputFile" type="file" onchange="convertToBase64();" />

<script type="text/javascript">
    function convertToBase64() {
        //Read File
        var selectedFile = document.getElementById("inputFile").files;
        //Check File is not Empty
        if (selectedFile.length > 0) {
            // Select the very first file from list
            var fileToLoad = selectedFile[0];
            // FileReader function for read the file.
            var fileReader = new FileReader();
            var base64;
            // Onload of file read the file content
            fileReader.onload = function(fileLoadedEvent) {
                base64 = fileLoadedEvent.target.result;
                // Print data in console
                console.log(base64);
            };
            // Convert data to base64
            fileReader.readAsDataURL(fileToLoad);
        }
    }
</script>

回答by onuryilmaz

Here is how one person did it:

这是一个人是如何做到的:

Here is a link that suggests several other possible solutions:

这是一个链接,建议了其他几种可能的解决方案: