Canvas 转 PDF——使用 JavaScript 将 HTML5 Canvas 导出为 PDF
Konva 绘制到 <canvas> 元素上,因此它导出的是像素。生成 PDF 有两种方式,请先确定你需要哪一种:
- 栅格方式:用于查看、分享或在办公打印机上打印的 PDF。 使用 jsPDF 将舞台的图像放入 PDF 文件。此示例展示了具体做法。
- 矢量方式:文本可选中的 PDF,或印刷级文件(文本和图形是真正的 PDF 对象,支持 CMYK、出血、裁切标记以及印刷厂要求的 PDF/X)。Konva 无法生成这种文件,放入 PDF 的图像也不会变成矢量。Polotno PDF 导出可生成矢量 PDF,支持 PDF/X-4、PDF/X-1a、CMYK 和出血。Polotno 是由 Konva 维护者基于 Konva 开发的商业设计编辑器 SDK。使用它并不需要编辑器。导出包接收设计的 JSON 描述,其格式与 Konva 节点相近:文本、图像、图形和线条,带有
x、y、rotation、fill和fontSize等属性。将你的舞台映射为这份 JSON,即可导出矢量 PDF。
栅格方式
生成 Canvas 内容,将舞台导出为图像,将该图像插入 PDF 文档,然后保存。使用 pixelRatio 属性让图像保持清晰。有关详细信息,请参阅高质量导出指南。
PDF 的页面是一张图像,因此放大到一定程度后会变模糊,其中的文本也无法选中。此示例为文本添加了一个简单的补救办法:先将每个文本节点写入 PDF,再将图像覆盖在上面,这样隐藏的文本就可以选中和搜索。复杂的文本样式无法完全对齐。
操作说明:查看下方 Canvas,然后单击按钮将其保存为 PDF。
- Vanilla
- React
- Vue
import Konva from 'konva';
import { jsPDF } from 'jspdf';
// Create a button for PDF export
const saveButton = document.createElement('button');
saveButton.textContent = 'Save as PDF';
saveButton.style.position = 'absolute';
saveButton.style.top = '5px';
saveButton.style.left = '5px';
document.body.appendChild(saveButton);
// Create a stage
const width = window.innerWidth;
const height = window.innerHeight;
const stage = new Konva.Stage({
container: 'container',
width: width,
height: height,
});
const layer = new Konva.Layer();
stage.add(layer);
// Add background
const back = new Konva.Rect({
width: stage.width(),
height: stage.height(),
fill: 'rgba(200, 200, 200)',
});
layer.add(back);
// Add text with blur effect
const text = new Konva.Text({
text: 'This is the Darth Vader',
x: 15,
y: 40,
rotation: -10,
filters: [Konva.Filters.Blur],
blurRadius: 4,
fontSize: 18,
});
text.cache();
layer.add(text);
// Add arrow
const arrow = new Konva.Arrow({
points: [70, 50, 100, 80, 150, 100, 190, 100],
tension: 0.5,
stroke: 'black',
fill: 'black',
});
layer.add(arrow);
// Add image
const imageUrl = 'https://konvajs.org/assets/darth-vader.jpg';
Konva.Image.fromURL(
imageUrl,
function (darthNode) {
darthNode.setAttrs({
x: 200,
y: 50,
scaleX: 0.5,
scaleY: 0.5,
});
layer.add(darthNode);
},
function () {
console.error('Failed to load image');
}
);
// Handle PDF export
saveButton.addEventListener('click', function () {
const pdf = new jsPDF({
orientation: 'landscape',
unit: 'px',
format: [stage.width(), stage.height()],
hotfixes: ['px_scaling'],
});
// Hidden text layer, so text can be selected and searched
pdf.setTextColor('#000000');
stage.find('Text').forEach((text) => {
const size = text.fontSize() * 0.75; // convert pixels to points
pdf.setFontSize(size);
pdf.text(text.text(), text.x(), text.y(), {
baseline: 'top',
angle: -text.getAbsoluteRotation(),
});
});
// The image goes on top and covers the text
pdf.addImage(
stage.toDataURL({ pixelRatio: 2 }),
0,
0,
stage.width(),
stage.height()
);
pdf.save('canvas.pdf');
});
import Konva from 'konva';
import { useEffect, useRef } from 'react';
import { Stage, Layer, Rect, Text, Arrow, Image } from 'react-konva';
import useImage from 'use-image';
import { jsPDF } from 'jspdf';
const App = () => {
const stageRef = useRef(null);
const textRef = useRef(null);
const [darthVaderImage] = useImage('https://konvajs.org/assets/darth-vader.jpg', 'anonymous');
const width = window.innerWidth;
const height = window.innerHeight;
useEffect(() => {
textRef.current?.cache();
}, []);
// Handle PDF export
const handleExport = () => {
if (stageRef.current) {
const stage = stageRef.current;
const pdf = new jsPDF({
orientation: 'landscape',
unit: 'px',
format: [width, height],
hotfixes: ['px_scaling'],
});
// Hidden text layer, so text can be selected and searched
pdf.setTextColor('#000000');
stage.find('Text').forEach((text) => {
const size = text.fontSize() * 0.75; // convert pixels to points
pdf.setFontSize(size);
pdf.text(text.text(), text.x(), text.y(), {
baseline: 'top',
angle: -text.getAbsoluteRotation(),
});
});
// The image goes on top and covers the text
pdf.addImage(
stage.toDataURL({ pixelRatio: 2 }),
0,
0,
width,
height
);
pdf.save('canvas.pdf');
} else {
console.error('Stage is not available');
}
};
return (
<div style={{ position: 'relative' }}>
<button
style={{ position: 'absolute', top: '5px', left: '5px', zIndex: 10 }}
onClick={handleExport}
>
Save as PDF
</button>
<Stage width={width} height={height} ref={stageRef}>
<Layer>
<Rect
width={width}
height={height}
fill="rgba(200, 200, 200)"
/>
<Text
ref={textRef}
text="This is the Darth Vader"
x={15}
y={40}
rotation={-10}
fontSize={18}
filters={[Konva.Filters.Blur]}
blurRadius={4}
/>
<Arrow
points={[70, 50, 100, 80, 150, 100, 190, 100]}
tension={0.5}
stroke="black"
fill="black"
/>
{darthVaderImage && (
<Image
image={darthVaderImage}
x={200}
y={50}
scaleX={0.5}
scaleY={0.5}
/>
)}
</Layer>
</Stage>
</div>
);
};
export default App;
<template>
<div style="position: relative">
<button
style="position: absolute; top: 5px; left: 5px; z-index: 10"
@click="handleExport"
>
Save as PDF
</button>
<v-stage ref="stageRef" :config="stageConfig">
<v-layer>
<v-rect :config="backgroundConfig" />
<v-text ref="textRef" :config="textConfig" />
<v-arrow :config="arrowConfig" />
<v-image
v-if="darthVaderImage"
:config="imageConfig"
/>
</v-layer>
</v-stage>
</div>
</template>
<script setup>
import { ref, onMounted, computed } from 'vue';
import Konva from 'konva';
import { useImage } from 'vue-konva';
import { jsPDF } from 'jspdf';
const stageRef = ref(null);
const textRef = ref(null);
const [darthVaderImage] = useImage('https://konvajs.org/assets/darth-vader.jpg', 'anonymous');
const width = window.innerWidth;
const height = window.innerHeight;
// Stage configuration
const stageConfig = {
width,
height
};
// Background configuration
const backgroundConfig = {
width,
height,
fill: 'rgba(200, 200, 200)'
};
// Text configuration
const textConfig = {
text: 'This is the Darth Vader',
x: 15,
y: 40,
rotation: -10,
fontSize: 18,
filters: [Konva.Filters.Blur],
blurRadius: 4
};
// Arrow configuration
const arrowConfig = {
points: [70, 50, 100, 80, 150, 100, 190, 100],
tension: 0.5,
stroke: 'black',
fill: 'black'
};
// Image configuration
const imageConfig = computed(() => ({
image: darthVaderImage.value,
x: 200,
y: 50,
scaleX: 0.5,
scaleY: 0.5
}));
onMounted(() => {
// Cache text for blur filter to work
if (textRef.value) {
textRef.value.getNode().cache();
}
});
// Handle PDF export
const handleExport = () => {
if (stageRef.value) {
const stage = stageRef.value.getNode();
const pdf = new jsPDF({
orientation: 'landscape',
unit: 'px',
format: [width, height],
hotfixes: ['px_scaling'],
});
// Hidden text layer, so text can be selected and searched
pdf.setTextColor('#000000');
stage.find('Text').forEach((text) => {
const size = text.fontSize() * 0.75; // convert pixels to points
pdf.setFontSize(size);
pdf.text(text.text(), text.x(), text.y(), {
baseline: 'top',
angle: -text.getAbsoluteRotation(),
});
});
// The image goes on top and covers the text
pdf.addImage(
stage.toDataURL({ pixelRatio: 2 }),
0,
0,
width,
height
);
pdf.save('canvas.pdf');
} else {
console.error('Stage is not available');
}
};
</script>