Вставка изображения в PDF с помощью jsPDF/HTML5 не работает

Я пытаюсь добавить изображение в PDF-файл, используя jsPDF-lib. PDF-файл создан, но изображение повреждено и выглядит следующим образом:

введите здесь описание изображения

Я использую тот же Data-URL в своем коде, что и в примере здесь: http://parall.ax/products/jspdf Мой полный код прикреплен ниже:

    <!DOCTYPE html>
<!--
    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you under the Apache License, Version 2.0 (the
    "License"); you may not use this file except in compliance
    with the License.  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing,
    software distributed under the License is distributed on an
    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
     KIND, either express or implied.  See the License for the
    specific language governing permissions and limitations
    under the License.
-->
<html>
    <head>
        <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
        <link rel="stylesheet" type="text/css" href="css/index.css" />
                <!-- Scripts down here -->
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
        <script type="text/javascript" src="jspdf.js"></script>
        <script type="text/javascript" src="jspdf.plugin.addimage.js"></script>
        <title>Hello World</title>
    </head>
    <body>
        <script type="text/javascript" src="cordova-2.7.0.js"></script>
        <script type="text/javascript">
        var doc;

        function clicked()  {
            doc = new jsPDF();
            var imgData = 'data:image/jpeg;base64, ***DATAURL_HERE***';
            doc.setFontSize(40);
            doc.text(35, 25, "Test-PDF");
            doc.addImage(imgData, 'JPEG', 15, 40, 180, 180);
            writeFile();
            alert("File was written");
            }

        function writeFile() {
            window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onFSSuccess, onError);
        }

        function onFSSuccess(fs) {
            fileSystem = fs;
            createRoot();            
        }

        function createRoot(e) {
            fileSystem.root.getDirectory("Download/", {create: true}, createFile);
        }

        function createFile(dirEntry) {
            var dir = "Test.pdf";
            dirEntry.getFile(dir, {create: true, exclusive: true}, saveFileToRoot);
        }

        function saveFileToRoot(f) {
            f.createWriter(function(writerOb) {
                writerOb.write(doc.output());
            });
        }

        function onError(e) {
        }

        </script>
    <h1>Testfile working</h1>
    <button onclick="clicked()">Clickme</button>
    </body>
</html>

Любые идеи!? Будем благодарны за любую помощь!


person Daniel Rausch    schedule 29.07.2013    source источник
comment
Итак ... вы можете опубликовать ссылку на исходное изображение?   -  person Ruslan López    schedule 19.02.2016


Ответы (1)


измените DATAURL_HERE на URL-изображение холста, вы можете рассчитать с помощью этой функции:

var imgData = canvas.toDataURL('image/png');

person seojedaperez    schedule 10.07.2017
comment
Пожалуйста, рассмотрите возможность пересмотра примера кода, который вы разместили в этом вопросе. В его нынешнем виде из-за его форматирования и объема нам сложно вам помочь; вот отличный ресурс, который поможет вам начать работу над этим. -1, не пойми неправильно. Голосование против — это то, как мы указываем здесь проблему с контентом; улучшите форматирование и образец кода, и я (или кто-то другой) с радостью верну его. Удачи с кодом! - person herrbischoff; 10.07.2017