Текст в столбцах таблицы обрезается в PDF-файле, созданном с помощью html2canvas и jsPDF. Как включить перенос слов?CSS

Разбираемся в CSS
Ответить Пред. темаСлед. тема
Anonymous
 Текст в столбцах таблицы обрезается в PDF-файле, созданном с помощью html2canvas и jsPDF. Как включить перенос слов?

Сообщение Anonymous »

Я использую html2canvas и jsPDF для создания PDF-файлов. Загруженный PDF-файл должен выглядеть как предварительный просмотр документа, но у меня возникли проблемы с макетом таблицы. В частности, текст в столбцах таблицы не переносится должным образом, в результате чего содержимое обрезается, и я не могу увидеть полный текст в этих столбцах. Я прикрепил изображение таблицы для справки. Как решить эту проблему, чтобы обеспечить правильный перенос текста в столбцах?
проверьте изображение здесь
Вот код:

Код: Выделить всё

export const downloadComponentAsPDF = async (elementId, fileName) => {
const contentArea = document.getElementById(elementId);

if (contentArea) {
try {
const pdf = new jsPDF({
orientation: 'portrait',
unit: 'pt',
format: 'a4',
});

const pdfWidth = pdf.internal.pageSize.getWidth();
const pdfHeight = pdf.internal.pageSize.getHeight();
const margin = 20;
const elementMargin = 10;
let positionY = margin;
let currentPageHeight = pdfHeight - 2 * margin;

// Group sections into rows based on layout
const rows = [];
let currentRow = [];
let currentRowWidth = 0;

const sections = Array.from(
contentArea.querySelectorAll('.section, .non-section'),
);

sections.forEach(section => {
const sectionWidth = parseInt(
section.getAttribute('data-width') || '12',
);

if (currentRowWidth + sectionWidth > 12) {
rows.push(currentRow);
currentRow = [];
currentRowWidth = 0;
}

currentRow.push(section);
currentRowWidth += sectionWidth;
});

if (currentRow.length > 0) {
rows.push(currentRow);
}

// Process each row and its sections in order
for (const row of rows) {
let rowHeight = 0;
const rowSections = [];

// Render sections in the current row
for (const section of row) {
const sectionWidth = parseInt(
section.getAttribute('data-width') || '12',
);
const sectionCanvas = await html2canvas(section, {
scale: 4,
useCORS: true,
});

const imgData = sectionCanvas.toDataURL('image/png');
const imgWidth = sectionCanvas.width;
const imgHeight = sectionCanvas.height;

const pdfImgWidth = (sectionWidth / 12) * (pdfWidth - 2 * margin);
const pdfImgHeight = (pdfImgWidth * imgHeight) / imgWidth;

rowHeight = Math.max(rowHeight, pdfImgHeight);
rowSections.push({
imgData,
pdfImgWidth,
pdfImgHeight,
sectionWidth,
});
}

// If row height exceeds current page height, create a new page
if (positionY + rowHeight > currentPageHeight) {
pdf.addPage();
positionY = margin;
currentPageHeight = pdfHeight - 2 * margin;
}

// Render the row in the PDF
let positionX = margin;
for (const rowSection of rowSections) {
pdf.addImage(
rowSection.imgData,
'PNG',
positionX,
positionY,
rowSection.pdfImgWidth,
rowHeight,
);

positionX += rowSection.pdfImgWidth + elementMargin;
}

positionY += rowHeight + elementMargin;
currentPageHeight -= rowHeight + elementMargin;
}

pdf.save(`${fileName}.pdf`);
} catch (error) {
console.error('Error generating PDF:', error);
}
}
};
Вот изображение, показывающее, как столбцы таблицы должны выглядеть в ожидаемом результате.

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

Подробнее здесь: https://stackoverflow.com/questions/790 ... -and-jspdf
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение
  • Шрифты не применяются в PDF-файле, созданном с использованием jsPDF из HTML-контента.
    Anonymous » » в форуме CSS
    0 Ответы
    31 Просмотры
    Последнее сообщение Anonymous
  • Шрифты не применяются в PDF-файле, созданном с использованием jsPDF из HTML-контента.
    Anonymous » » в форуме CSS
    0 Ответы
    30 Просмотры
    Последнее сообщение Anonymous
  • Как получить многостраничный PDF-файл с веб-сайта, используя jsPDF и HTML2Canvas?
    Anonymous » » в форуме Jquery
    0 Ответы
    21 Просмотры
    Последнее сообщение Anonymous
  • Текст обрезается при захвате div с помощью html2canvas
    Anonymous » » в форуме Html
    0 Ответы
    2 Просмотры
    Последнее сообщение Anonymous
  • Html2canvas и jspdf не представляют значения Lightning combobox в приложении LWR
    Anonymous » » в форуме Javascript
    0 Ответы
    1 Просмотры
    Последнее сообщение Anonymous

Вернуться в «CSS»