В моем reactJS я хочу преобразовать свой DOM (и часть) моего DOM в PDF. Мне нужен удобочитаемый и выбираемый PDF-файл, и я не хочу терять стиль CSS.
Я пробовал это:
const input = document.getElementById('toPdf');
let doc = new jsPDF("portrait", "mm", "a4");
doc.fromHTML(input, 1, 1);
doc.save("myDocument.pdf");
Это мило. Его читаемый, многостраничный и текст можно выбрать. Но это теряет полный стиль.
Результат:
Есть ли способ сохранить стиль?
Мой HTML выглядит так:
Я использую это: jsPDF
Заранее спасибо.
Ошибки обновления:
Uncaught (in promise) ReferenceError: pdf is not defined
at Object.callback (RaUpdateSendReportMethods.js?ea2d:54)
at Promise.eval (jspdf.min.js?b003:118)
callback @ RaUpdateSendReportMethods.js?ea2d:54
(anonymous) @ jspdf.min.js?b003:118
Promise.then (async)
(anonymous) @ jspdf.min.js?b003:118
y.thenCore @ jspdf.min.js?b003:118
y.then @ jspdf.min.js?b003:118
y.doCallback @ jspdf.min.js?b003:118
i.html @ jspdf.min.js?b003:118
createPDF @ RaUpdateSendReportMethods.js?ea2d:51
onClick @ RaUpdateSendReport.js?3ca0:238
EnhancedButton._this.handleClick @ EnhancedButton.js?7315:138
boundFunc @ ReactErrorUtils.js?dc41:63
ReactErrorUtils.invokeGuardedCallback @ ReactErrorUtils.js?dc41:69
executeDispatch @ EventPluginUtils.js?5d8c:83
executeDispatchesInOrder @ EventPluginUtils.js?5d8c:106
executeDispatchesAndRelease @ EventPluginHub.js?0f32:41
executeDispatchesAndReleaseTopLevel @ EventPluginHub.js?0f32:52
forEachAccumulated @ forEachAccumulated.js?e2c3:22
processEventQueue @ EventPluginHub.js?0f32:252
runEventQueueInBatch @ ReactEventEmitterMixin.js?91f8:15
handleTopLevel @ ReactEventEmitterMixin.js?91f8:25
handleTopLevelImpl @ ReactEventListener.js?944f:70
perform @ Transaction.js?f15f:141
batchedUpdates @ ReactDefaultBatchingStrategy.js?e9be:60
batchedUpdates @ ReactUpdates.js?8e6b:95
dispatchEvent @ ReactEventListener.js?944f:145
html2canvas.min.js:7 html2canvas: Preload starts: finding background-images
html2canvas.min.js:7 html2canvas.Util.Children failed with exception: Cannot read property 'document' of null
html2canvas.min.js:7 html2canvas: Preload: Finding images
html2canvas.min.js:7 html2canvas: Preload: Done.
html2canvas.min.js:7 html2canvas: start: images: 0 / 0 (failed: 0)
html2canvas.min.js:7 Finished loading images: # 0 (failed: 0)
html2canvas.min.js:7 html2canvas: Renderer: Canvas renderer done - returning canvas obj
html2canvas.min.js:8 Uncaught TypeError: Failed to execute 'drawImage' on
'CanvasRenderingContext2D': The provided value is not of type '(CSSImageValue or HTMLImageElement or SVGImageElement or HTMLVideoElement or HTMLCanvasElement or ImageBitmap or OffscreenCanvas)'
at html2canvas.min.js:8
at Object.u.Renderer (html2canvas.min.js:8)
at Object.o.complete (html2canvas.min.js:8)
at o (html2canvas.min.js:7)
at Object.u.Preload (html2can
vas.min.js:7)
at html2canvas.min.js:8
спасибо, но я не вижу, где разница, которая сохраняет стиль



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Попробуйте jsPDF .html() вместо .fromHtml().
<script src = "https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.debug.js"
integrity = "sha384-NaWTHo/8YCBYJ59830LTz/P4aQZK1sS0SneOgAvhsIl3zBu8r9RevNg5lHCHAuQ/"
crossorigin = "anonymous"></script>
<script src = "~/lib/html2canvas/html2canvas.min.js"></script></script>
<!-- html2canvas 1.0.0-alpha.11 up to v1.0.0-rc.1 works, current version may not work -->
<script>
function download() {
let pdf = new jsPDF('p', 'pt', 'letter');
pdf.html(document.getElementById('toPdf'), {
callback: function () {
pdf.save('myDocument.pdf');
window.open(pdf.output('bloburl')); // To debug.
}
});
}
</script>
Могу ли я также передать определенный файл CSS? изменить некоторые вещи из отображаемой версии?
еще не могу Завтра протестировать ... ПК дома только смартфон ;) ... попробую завтра утром
понимать. Вы можете обратиться к этому отвечать об изменении css. Однако это не имеет ничего общего с jspdf, чистый JavaScript.
когда я делаю это, как указано выше, я получаю ошибки, я добавляю их выше
Теперь у меня новая ошибка html2canvas.min.js:6 Uncaught (in promise) DOMException: Failed to execute 'setEnd' on 'Range': The offset 24 is larger than the node's length (23). есть подсказка для меня?
голосование против, потому что .html не найден, возможно, без сборки библиотеки и даже с проблемами. Не правильное решение.
Посмотрите на этот пример и попробуйте -> codementor.io/amehjoseph/…