jsPDF разбить JPG на страницы - PullRequest
0 голосов
/ 01 мая 2020

У меня есть скриншот jpeg веб-страницы, которую я пытаюсь превратить в pdf с jsPdf.

Изображение имеет высоту 21873 пикселей в соответствии с измерением offsetHeight элемента div контейнера страницы.

Нижняя часть изображения имеет размер 2572 пикселя и всегда одинаковую высоту. Высота других частей изображения может варьироваться.

Я пытался поэкспериментировать с тем, как нижняя часть отображается в pdf. Я получаю неплохие результаты, если предположить, что нижний бит имеет высоту 9100 пикселей (хотя он все еще имеет размер 2572 по offsetHeight), а общая высота изображения, измеренная от исходного offsetHeight, равна 18094:

let node = reportInViewerRef.current;
let reportHeight = reportInViewerRef.current.scrollHeight
let reportWidth = reportInViewerRef.current.offsetWidth

let imgHeight = reportHeight

if (reportHeight >= 14400) {
    imgHeight = reportHeight - 9100
}
console.log("REPORT HEIGHT", reportHeight)

domtoimage.toJpeg(node, {width: reportInViewerRef.current.offsetWidth, height: reportInViewerRef.current.scrollHeight})
.then(function (dataUrl) {
    const pdf = new jsPDF('p', 'px', [reportWidth, imgHeight]);

    pdf.addImage(dataUrl, 'JPEG', 0, -12, reportWidth, reportHeight );
    pdf.addPage([reportWidth, imgHeight]);
    pdf.setPage(2);
    pdf.addImage(dataUrl, 'JPEG', 0, -imgHeight, reportWidth, reportHeight);

Как только я попробуйте разбить изображения разного размера на страницы переменной высоты, все это разбивается.

Следующий код выдает PDF-файл, в котором первая страница pdf всегда имеет максимальную высоту, а остальные страницы остаются пустыми:

let node = reportInViewerRef.current;
let reportHeight = reportInViewerRef.current.scrollHeight
let reportWidth = reportInViewerRef.current.offsetWidth

let imgHeight = Math.min(9100, reportHeight - 9100)
let pages = Math.floor(reportHeight / imgHeight)

console.log("REPORT HEIGHT", reportHeight, pages)

domtoimage.toJpeg(node, {width: reportInViewerRef.current.offsetWidth, height: reportInViewerRef.current.scrollHeight})
.then(function (dataUrl) {
    const pdf = new jsPDF('p', 'px', [reportWidth, imgHeight]);

    pdf.addImage(dataUrl, 'JPEG', 0, -12, reportWidth, reportHeight );
    pdf.addPage([reportWidth, imgHeight]);
    if (pages > 1) {
        for (let i=0; i<pages; i++) {
            pdf.setPage(i);
            pdf.addPage([reportWidth, imgHeight]);
            pdf.addImage(dataUrl, 'JPEG', 0, -imgHeight * i, reportWidth, reportHeight);
        }
    }

Я вообще не могу понять, что происходит с измерениями - любая помощь?

Когда я умножаю на 0,65 примерно так:

let reportHeight = reportInViewerRef.current.scrollHeight * 0.65
let reportWidth = reportInViewerRef.current.offsetWidth * 0.65

все подходит, хотя разрешение выглядит ниже ???

И что бы я ни делал, высота прокрутки в браузере всегда огромна - много пустого пространства внизу?

...