Commit daedde51 by ramdayalmunda

PDF generated from canvas

parent d056325e
...@@ -31,7 +31,7 @@ var ADocEditor = function (customConfig) { ...@@ -31,7 +31,7 @@ var ADocEditor = function (customConfig) {
tabWidth: 20, tabWidth: 20,
}, },
style: { style: {
fontSize: 12, fontSize: 16,
fontFamily: 'customfont', fontFamily: 'customfont',
bold: false, bold: false,
italic: false, italic: false,
...@@ -58,7 +58,180 @@ var ADocEditor = function (customConfig) { ...@@ -58,7 +58,180 @@ var ADocEditor = function (customConfig) {
dataSet = JSON.parse('[{"id":1,"type":0,"formatedText":[],"plainContent":"Rendering text in HTML canvas involves using the CanvasRenderingContext2D interface to display text content within a canvas element. This process allows for dynamic text display, enabling the creation of custom text effects, labels, captions, or textual elements within the canvas.","style":{"fontSize":12,"fontFamily":"customfont","bold":false,"italic":false,"fontColor":"#001"}},{"id":2,"type":0,"plainContent":"To render text on a canvas, developers typically use the fillText() method provided by the Canvas API. This method allows the specification of text content, font styles, position, and color. Additionally, the measureText() method helps in determining the width of text, facilitating accurate positioning and layout arrangements.","style":{"fontSize":12,"fontFamily":"customfont","bold":false,"italic":false,"fontColor":"#001"}},{"id":3,"type":0,"plainContent":"Text in canvas can be customized by setting various font properties like font family, font size, style (bold, italic), alignment, and color. However, canvas text rendering lacks the text reflow and responsive layout capabilities inherent in HTML and CSS.","style":{"fontSize":12,"fontFamily":"customfont","bold":false,"italic":false,"fontColor":"#001"}},{"id":4,"type":0,"plainContent":"Despite its intricacies, canvas text rendering offers unparalleled creative freedom, enabling the development of immersive graphical experiences, custom typography, and visually stunning representations that enhance user engagement and interactivity within web-based applications and games.","style":{"fontSize":12,"fontFamily":"customfont","bold":false,"italic":false,"fontColor":"#001"}},{"id":5,"type":0,"plainContent":"Developers often use canvas text rendering to create graphical representations of text-based information, such as game interfaces, data visualizations, charts, and diagrams. Despite its flexibility in text manipulation and artistic possibilities, rendering text in canvas may require additional manual adjustments for formatting, spacing, and alignment compared to traditional HTML text rendering.","style":{"fontSize":12,"fontFamily":"customfont","bold":false,"italic":false,"fontColor":"#001"}}]') dataSet = JSON.parse('[{"id":1,"type":0,"formatedText":[],"plainContent":"Rendering text in HTML canvas involves using the CanvasRenderingContext2D interface to display text content within a canvas element. This process allows for dynamic text display, enabling the creation of custom text effects, labels, captions, or textual elements within the canvas.","style":{"fontSize":12,"fontFamily":"customfont","bold":false,"italic":false,"fontColor":"#001"}},{"id":2,"type":0,"plainContent":"To render text on a canvas, developers typically use the fillText() method provided by the Canvas API. This method allows the specification of text content, font styles, position, and color. Additionally, the measureText() method helps in determining the width of text, facilitating accurate positioning and layout arrangements.","style":{"fontSize":12,"fontFamily":"customfont","bold":false,"italic":false,"fontColor":"#001"}},{"id":3,"type":0,"plainContent":"Text in canvas can be customized by setting various font properties like font family, font size, style (bold, italic), alignment, and color. However, canvas text rendering lacks the text reflow and responsive layout capabilities inherent in HTML and CSS.","style":{"fontSize":12,"fontFamily":"customfont","bold":false,"italic":false,"fontColor":"#001"}},{"id":4,"type":0,"plainContent":"Despite its intricacies, canvas text rendering offers unparalleled creative freedom, enabling the development of immersive graphical experiences, custom typography, and visually stunning representations that enhance user engagement and interactivity within web-based applications and games.","style":{"fontSize":12,"fontFamily":"customfont","bold":false,"italic":false,"fontColor":"#001"}},{"id":5,"type":0,"plainContent":"Developers often use canvas text rendering to create graphical representations of text-based information, such as game interfaces, data visualizations, charts, and diagrams. Despite its flexibility in text manipulation and artistic possibilities, rendering text in canvas may require additional manual adjustments for formatting, spacing, and alignment compared to traditional HTML text rendering.","style":{"fontSize":12,"fontFamily":"customfont","bold":false,"italic":false,"fontColor":"#001"}}]')
// // lists // this line is added only for testing please remove this on completion // // lists // this line is added only for testing please remove this on completion
dataSet = JSON.parse('[{"id":1,"type":0,"plainContent":"Here is a list of household items you need to buy if you are relocating and don\'t have anything with you but you still want go there and settle down.","style":{"fontSize":12,"fontFamily":"customfont","bold":false,"italic":false,"fontColor":"#003"},"formatedText":[]},{"id":2,"type":1,"tabCount":0,"plainContent":"Recipie book for vegetarian noodles","style":{"fontSize":12,"fontFamily":"customfont","bold":false,"italic":false,"fontColor":"#003"},"formatedText":[]},{"id":3,"type":1,"tabCount":0,"plainContent":"Noodles","style":{"fontSize":12,"fontFamily":"customfont","bold":false,"italic":false,"fontColor":"#003"},"formatedText":[]},{"id":5,"type":1,"tabCount":0,"plainContent":"Garlic","style":{"fontSize":12,"fontFamily":"customfont","bold":false,"italic":false,"fontColor":"#003"},"formatedText":[]},{"id":6,"type":1,"tabCount":0,"plainContent":"Some School stationaries for Arvind","style":{"fontSize":12,"fontFamily":"customfont","bold":false,"italic":false,"fontColor":"#003"},"formatedText":[]},{"id":7,"type":1,"tabCount":1,"plainContent":"Full pack of pen","style":{"fontSize":12,"fontFamily":"customfont","bold":false,"italic":false,"fontColor":"#003"},"formatedText":[]},{"id":8,"type":1,"tabCount":1,"plainContent":"Drawing kit","style":{"fontSize":12,"fontFamily":"customfont","bold":false,"italic":false,"fontColor":"#003"},"formatedText":[]},{"id":9,"type":1,"tabCount":1,"plainContent":"2 register size notebook","style":{"fontSize":12,"fontFamily":"customfont","bold":false,"italic":false,"fontColor":"#003"},"formatedText":[]},{"id":10,"type":1,"tabCount":0,"plainContent":"Window shields","style":{"fontSize":12,"fontFamily":"customfont","bold":false,"italic":false,"fontColor":"#003"},"formatedText":[]},{"id":11,"type":1,"tabCount":0,"plainContent":"Mosquito repelant","style":{"fontSize":12,"fontFamily":"customfont","bold":false,"italic":false,"fontColor":"#003"},"formatedText":[]}]') dataSet = JSON.parse('[{"id":1,"type":0,"plainContent":"Here is a list of household items you need to buy if you are relocating and don\'t have anything with you but you still want go there and settle down.","style":{"fontSize":12,"fontFamily":"customfont","bold":false,"italic":false,"fontColor":"#003"},"formatedText":[]},{"id":2,"type":1,"tabCount":0,"plainContent":"Recipie book for vegetarian noodles","style":{"fontSize":12,"fontFamily":"customfont","bold":false,"italic":false,"fontColor":"#003"},"formatedText":[]},{"id":3,"type":1,"tabCount":0,"plainContent":"Noodles","style":{"fontSize":12,"fontFamily":"customfont","bold":false,"italic":false,"fontColor":"#003"},"formatedText":[]},{"id":5,"type":1,"tabCount":0,"plainContent":"Garlic","style":{"fontSize":12,"fontFamily":"customfont","bold":false,"italic":false,"fontColor":"#003"},"formatedText":[]},{"id":6,"type":1,"tabCount":0,"plainContent":"Some School stationaries for Arvind","style":{"fontSize":12,"fontFamily":"customfont","bold":false,"italic":false,"fontColor":"#003"},"formatedText":[]},{"id":7,"type":1,"tabCount":1,"plainContent":"Full pack of pen","style":{"fontSize":12,"fontFamily":"customfont","bold":false,"italic":false,"fontColor":"#003"},"formatedText":[]},{"id":8,"type":1,"tabCount":1,"plainContent":"Drawing kit","style":{"fontSize":12,"fontFamily":"customfont","bold":false,"italic":false,"fontColor":"#003"},"formatedText":[]},{"id":9,"type":1,"tabCount":1,"plainContent":"2 register size notebook","style":{"fontSize":12,"fontFamily":"customfont","bold":false,"italic":false,"fontColor":"#003"},"formatedText":[]},{"id":10,"type":1,"tabCount":0,"plainContent":"Window shields","style":{"fontSize":12,"fontFamily":"customfont","bold":false,"italic":false,"fontColor":"#003"},"formatedText":[]},{"id":11,"type":1,"tabCount":0,"plainContent":"Mosquito repelant","style":{"fontSize":12,"fontFamily":"customfont","bold":false,"italic":false,"fontColor":"#003"},"formatedText":[]}]')
dataSet = [
{
id: ++counter, type: 0, style: { ...config.style }, formatedText: [],
plainContent: "Sarah: Alex, we need some groceries from the store. Could you please go and get them?",
},
{
id: ++counter, type: 0, style: { ...config.style }, formatedText: [],
plainContent: "Alex: (Without looking up from his laptop) Mom, I'm right in the middle of something important. Can't it wait?",
},
{
id: ++counter, type: 0, style: { ...config.style }, formatedText: [],
plainContent: "Sarah: (Smiling) I understand, dear. But I've got a lot to do here, and it'd be a great help if you could pick up the groceries.",
},
{
id: ++counter, type: 0, style: { ...config.style }, formatedText: [],
plainContent: "Alex: (Sighing) Can't we go later? I've got this project deadline...",
},
{
id: ++counter, type: 0, style: { ...config.style }, formatedText: [],
plainContent: "Sarah: (Interrupting gently) Alex, we're running low on essentials. It won't take much time. Plus, some fresh air might do you good after being glued to your laptop for hours.",
},
{
id: ++counter, type: 0, style: { ...config.style }, formatedText: [],
plainContent: "Alex: (Reluctantly) But it's your day off, Mom. You should relax.",
},
{
id: ++counter, type: 0, style: { ...config.style }, formatedText: [],
plainContent: "Sarah: (Chuckling) Relaxing is fetching groceries? No worries, it's alright. I can go.",
},
{
id: ++counter, type: 0, style: { ...config.style }, formatedText: [],
plainContent: "Alex: (Feeling guilty) No, no, I'll go. Just let me finish this task, okay?",
},
{
id: ++counter, type: 0, style: { ...config.style }, formatedText: [],
plainContent: "Sarah: (Smiling warmly) Thanks, dear. I really appreciate it.",
},
{
id: ++counter, type: 0, style: { ...config.style }, formatedText: [],
plainContent: "They share a smile, and Alex closes his laptop, heading out to the store.",
},
{
id: ++counter, type: 0, style: { ...config.style }, formatedText: [],
plainContent: "Sarah: (Calling after him) Don't forget the list!",
},
{
id: ++counter, type: 0, style: { ...config.style }, formatedText: [],
plainContent: "Alex waves in acknowledgment and leaves, while Sarah returns to her cooking, content that the groceries will soon be sorted. Alex looks at the list, there were a lot of items on the list.",
},
{
id: ++counter, type: 1, style: { ...config.style }, formatedText: [],
plainContent: "Vegetables", tabCount: 0,
},
{
id: ++counter, type: 1, style: { ...config.style }, formatedText: [],
plainContent: "Carrots", tabCount: 1,
},
{
id: ++counter, type: 1, style: { ...config.style }, formatedText: [],
plainContent: "Broccli", tabCount: 1,
},
{
id: ++counter, type: 1, style: { ...config.style }, formatedText: [],
plainContent: "Bell Peppers", tabCount: 1,
},
{
id: ++counter, type: 1, style: { ...config.style }, formatedText: [],
plainContent: "Fruits", tabCount: 0,
},
{
id: ++counter, type: 1, style: { ...config.style }, formatedText: [],
plainContent: "Apples", tabCount: 1,
},
{
id: ++counter, type: 1, style: { ...config.style }, formatedText: [],
plainContent: "Oranges", tabCount: 1,
},
{
id: ++counter, type: 1, style: { ...config.style }, formatedText: [],
plainContent: "Dairy", tabCount: 0,
},
{
id: ++counter, type: 1, style: { ...config.style }, formatedText: [],
plainContent: "Milk", tabCount: 1,
},
{
id: ++counter, type: 1, style: { ...config.style }, formatedText: [],
plainContent: "Cheese", tabCount: 1,
},
{
id: ++counter, type: 1, style: { ...config.style }, formatedText: [],
plainContent: "Yogurt", tabCount: 1,
},
{
id: ++counter, type: 1, style: { ...config.style }, formatedText: [],
plainContent: "Household", tabCount: 0,
},
{
id: ++counter, type: 1, style: { ...config.style }, formatedText: [],
plainContent: "Cottonelle Toilet Paper (Pack of 6). Make sure to bring the items where each pack has 100 meter rolls.", tabCount: 1,
},
{
id: ++counter, type: 1, style: { ...config.style }, formatedText: [],
plainContent: "Mrs. Meyer's Lemon Verbena Dish Soap", tabCount: 1,
},
{
id: ++counter, type: 1, style: { ...config.style }, formatedText: [],
plainContent: "Tide Free & Gentle Laundry Detergent", tabCount: 1,
},
{
id: ++counter, type: 1, style: { ...config.style }, formatedText: [],
plainContent: "Bakery", tabCount: 0,
},
{
id: ++counter, type: 1, style: { ...config.style }, formatedText: [],
plainContent: "Bread", tabCount: 1,
},
{
id: ++counter, type: 1, style: { ...config.style }, formatedText: [],
plainContent: "Bagels", tabCount: 1,
},
{
id: ++counter, type: 0, style: { ...config.style }, formatedText: [],
plainContent: "Once Alex stepped out of his house, he felt the crisp autumn air greet him. Armed with his phone displaying Sarah's detailed grocery list, he set off on his mission to the nearby supermarket.",
},
{
id: ++counter, type: 0, style: { ...config.style }, formatedText: [],
plainContent: "The store was bustling with shoppers, but Alex navigated through the aisles with purpose. He began in the produce section, carefully selecting the freshest carrots, crisp broccoli, and vibrant red bell peppers. He lingered a moment longer in the fruit section, examining each apple, banana, and orange to ensure they met the criteria on Sarah's list.",
},
{
id: ++counter, type: 0, style: { ...config.style }, formatedText: [],
plainContent: "With the vegetables and fruits secured, he made his way to the dairy aisle. He picked up the specified 2% organic milk, sharp cheddar cheese, and Greek vanilla yogurt, double-checking the brands to match Sarah's preferences.",
},
{
id: ++counter, type: 0, style: { ...config.style }, formatedText: [],
plainContent: "Next on the list were bakery items. He chose a loaf of whole-grain bread and a pack of everything bagels, making sure they were fresh before moving on to the pantry essentials. Penne pasta, Basmati rice, fire-roasted diced tomatoes, and honey nut crunch cereal found their way into his cart.",
},
{
id: ++counter, type: 0, style: { ...config.style }, formatedText: [],
plainContent: "As he moved to the meat and protein section, he carefully selected free-range chicken breasts, a pound of lean ground beef, and a dozen farm-fresh eggs, ensuring they met the quality standards Sarah had in mind.",
},
{
id: ++counter, type: 0, style: { ...config.style }, formatedText: [],
plainContent: "After collecting household items like cottonelle toilet paper, Mrs. Meyer's lemon verbena dish soap, and Tide Free & Gentle laundry detergent, Alex made his way to the checkout counter. The cashier scanned each item, and Alex packed them meticulously into bags, arranging delicate produce separately to prevent any damage.",
},
{
id: ++counter, type: 0, style: { ...config.style }, formatedText: [],
plainContent: "Balancing the bags on his arms, Alex made his way back home. The sky had turned a warm orange hue as the sun began to set. He navigated through the busy streets, feeling a sense of accomplishment for successfully checking off every item on Sarah's exhaustive list.",
},
{
id: ++counter, type: 0, style: { ...config.style }, formatedText: [],
plainContent: "As he approached his house, he could already smell the aroma of the dinner Sarah was preparing. Alex walked in, slightly out of breath but proud of his successful grocery run.",
},
{
id: ++counter, type: 0, style: { ...config.style }, formatedText: [],
plainContent: `"Hey, Mom, I'm back!" he called out.`,
},
{
id: ++counter, type: 0, style: { ...config.style }, formatedText: [],
plainContent: `Sarah, busy at the stove, turned around, beaming. "Oh, Alex, you're a lifesaver! Did you manage to get everything?"`,
},
{
id: ++counter, type: 0, style: { ...config.style }, formatedText: [],
plainContent: `"Absolutely," Alex replied, setting the bags down on the counter. "And I even got the specific brands and types you asked for!"`,
},
{
id: ++counter, type: 0, style: { ...config.style }, formatedText: [],
plainContent: `Sarah gave him a grateful smile. "Thank you so much, Alex. You're a star! Now, dinner will be ready in no time."`,
},
{
id: ++counter, type: 0, style: { ...config.style }, formatedText: [],
plainContent: `As they unpacked the groceries together, Sarah couldn't help but appreciate her thoughtful son's effort and attention to detail, making the task much more manageable and enjoyable for her.`,
},
]
var lines = [] var lines = []
var caretData = { var caretData = {
...@@ -81,7 +254,6 @@ var ADocEditor = function (customConfig) { ...@@ -81,7 +254,6 @@ var ADocEditor = function (customConfig) {
config.pageSetup.fontMultiplier = config.pageSetup.canvasMultiplier / 3 config.pageSetup.fontMultiplier = config.pageSetup.canvasMultiplier / 3
config.pageSetup.canvasWidth = config.pageSetup.canvasMultiplier * config.pageSetup.width config.pageSetup.canvasWidth = config.pageSetup.canvasMultiplier * config.pageSetup.width
config.pageSetup.canvasHeight = config.pageSetup.canvasMultiplier * config.pageSetup.height config.pageSetup.canvasHeight = config.pageSetup.canvasMultiplier * config.pageSetup.height
console.log('pageSetup:', config.pageSetup)
if (!isModule) { if (!isModule) {
if (!config.element) throw "'container' not provided in the config" if (!config.element) throw "'container' not provided in the config"
if (typeof config.element == 'string') container = document.querySelector(config.element) if (typeof config.element == 'string') container = document.querySelector(config.element)
...@@ -208,18 +380,20 @@ var ADocEditor = function (customConfig) { ...@@ -208,18 +380,20 @@ var ADocEditor = function (customConfig) {
// to calculate the lines // to calculate the lines
let dataLineArr = [] let dataLineArr = []
function getLineObj() { function getLineObj() {
return {
let newLineObj = {
...config.style,
x: 0, // this is the starting point x; it will change based on the tabNumber x: 0, // this is the starting point x; it will change based on the tabNumber
y: 0, // this is the starting y coordinate; it will change based on the max font size y: 0, // this is the starting y coordinate; it will change based on the max font size
plainContent: "", plainContent: "",
fontSize: 12,
maxFontSize: 12,
dataSetIndex: dataSetIndex, dataSetIndex: dataSetIndex,
charStartIndex: 0, // index from where to check charStartIndex: 0, // index from where to check
charEndIndex: 0, // index till where to check// not including this index. charEndIndex: 0, // index till where to check// not including this index.
} }
newLineObj.maxFontSize = newLineObj.fontSize
return newLineObj
} }
if (!dataBlock.formatedText) dataBlock.formatedText = [] if (!dataBlock.formatedText) dataBlock.formatedText = []
let lineObj = new getLineObj() let lineObj = new getLineObj()
...@@ -637,38 +811,105 @@ var ADocEditor = function (customConfig) { ...@@ -637,38 +811,105 @@ var ADocEditor = function (customConfig) {
} }
async function generatePDF(file) { async function generatePDF(file) {
if (isModule) { const customFontDataURI = await getFontDataURI("./assets/fonts/customfont.ttf")
try {
const { jsPDF } = require("jspdf") const { jsPDF } = jspdf;
console.log('to generate PDF on Server side:', file)
const doc = new jsPDF(config.pageSetup.orientation, 'px', [config.pageSetup.canvasWidth, config.pageSetup.canvasHeight]);
// Default export is a4 paper, portrait, using millimeters for units
const fontFilePath = path.join(__dirname, 'fonts', 'customfont.ttf') const doc = new jsPDF({
// const fontFileContent = fs.readFileSync(fontFilePath); orientation: "p",
doc.addFont(fontFilePath, 'customfont', 'normal'); unit: "px",
doc.setFont('customfont'); hotfixes: ["px_scaling"],
doc.setFontSize(100) format: [config.pageSetup.canvasWidth, config.pageSetup.canvasHeight]
doc.text('Hello World', 100, 100); });
doc.save(file) let customFontName = "customfont"
return file doc.addFileToVFS('customfont.ttf', customFontDataURI); // Add the font to the Virtual File System
} catch (err) { doc.addFont('customfont.ttf', customFontName, 'normal');
console.log(err)
return let canvasIndex = 0
let x = 0
let y = (config.format.margin * config.pageSetup.canvasMultiplier)
let maxVericalWidth = (config.pageSetup.canvasHeight - config.format.margin * config.pageSetup.canvasMultiplier * 2)
for (let l = 0; l < lines.length; l++) {
x = (config.format.margin * config.pageSetup.canvasMultiplier);
y += (lines[l].maxFontSize * config.pageSetup.fontMultiplier)
if (lines[l].blockStart && l != 0) y += lines[l].maxFontSize
if ((maxVericalWidth + lines[l].maxFontSize) < (y - lines[l].maxFontSize)) {
canvasIndex++
doc.addPage()
y = lines[l].maxFontSize + (config.format.margin * config.pageSetup.canvasMultiplier)
}
let setData = dataSet[lines[l].dataSetIndex]
lines[l].y = y
if (lines[l].listIndex >= 0) {
let totalTabDistance = config.format.tabWidth * config.pageSetup.canvasMultiplier * (lines[l].tabCount + 1)
x += totalTabDistance;
let numberX = x - config.format.tabWidth * config.pageSetup.canvasMultiplier / 2
if (lines[l].blockStart) {
let style = {
...config.style,
...setData.style
}
doc.setFont( style.fontFamily )
doc.setFontSize( style.fontSize*3/2 )
doc.text( `${lines[l].listIndex + 1}.`, numberX, y)
}
}
lines[l].x = x
lines[l].canvasIndex = canvasIndex
for (let c = lines[l].charStartIndex; c <= lines[l].charEndIndex; c++) {
let char = setData?.plainContent[c]
if (char) {
let style = setData.formatedText[c]
doc.setFont( style.fontFamily )
doc.setFontSize( style.fontSize*3/2 )
doc.text( char, x, y )
setData.formatedText[c].x = x
setData.formatedText[c].y = y
if (setData.formatedText[c]?.width) {
x += setData.formatedText[c]?.width
}
}
} }
} else {
console.log('to generate PDF on browser:', file) }
doc.save(file)
async function getFontDataURI(url) {
return new Promise(async (res, rej) => {
fetch('./assets/fonts/customfont.ttf')
.then(response => response.blob())
.then(blob => {
const reader = new FileReader();
reader.readAsDataURL(blob);
reader.onloadend = () => {
res(reader.result.split(',')[1])
}
})
.catch((err) => { rej(err) })
})
} }
} }
function addFonts(paths, name) { function addFonts(paths, name) {
console.log('to add font', paths, name)
if (!isModule) { if (!isModule) {
console.log('existings', fontList) if (fontList.find(item => item.name.toLowerCase() == name.toLowerCase())) {
if ( fontList.find( item => item.name.toLowerCase()==name.toLowerCase() ) ){ throw "Font: Already Exists"
console.log('Font already exists')
return
} }
...@@ -677,31 +918,31 @@ var ADocEditor = function (customConfig) { ...@@ -677,31 +918,31 @@ var ADocEditor = function (customConfig) {
font-family: '${name}'; font-family: '${name}';
src: src:
` `
if (typeof paths == 'object'){ if (typeof paths == 'object') {
for (let i=0; i<paths.length; i++) { for (let i = 0; i < paths.length; i++) {
let linkTag = document.createElement('link') let linkTag = document.createElement('link')
linkTag.onload = ()=>{ reRenderPages(dataSet) } linkTag.onload = () => { reRenderPages(dataSet) }
linkTag.href = paths[i] linkTag.href = paths[i]
linkTag.rel = "stylesheet" linkTag.rel = "stylesheet"
document.head.append(linkTag) document.head.append(linkTag)
let splitted = paths[i].split('.') let splitted = paths[i].split('.')
let format = splitted[splitted.length-1] let format = splitted[splitted.length - 1]
format = format=='ttf'?'truetype':format format = format == 'ttf' ? 'truetype' : format
newStyle +=`url('${paths[i]}') format('${format}')${(i==paths.length-1)?';':','} newStyle += `url('${paths[i]}') format('${format}')${(i == paths.length - 1) ? ';' : ','}
` `
} }
}else{ } else {
let linkTag = document.createElement('link') let linkTag = document.createElement('link')
linkTag.onload = ()=>{ reRenderPages(dataSet) } linkTag.onload = () => { reRenderPages(dataSet) }
linkTag.href = paths linkTag.href = paths
let splitted = paths.split('.') let splitted = paths.split('.')
document.head.append(linkTag) document.head.append(linkTag)
let format = splitted[splitted.length-1] let format = splitted[splitted.length - 1]
format = format=='ttf'?'truetype':format format = format == 'ttf' ? 'truetype' : format
newStyle+=`url('${paths}') format('${format}');` newStyle += `url('${paths}') format('${format}');`
} }
newStyle+=` newStyle += `
} }
` `
styleTag.textContent = newStyle styleTag.textContent = newStyle
...@@ -732,8 +973,8 @@ var ADocEditor = function (customConfig) { ...@@ -732,8 +973,8 @@ var ADocEditor = function (customConfig) {
return JSON.parse(JSON.stringify(dataSet)) return JSON.parse(JSON.stringify(dataSet))
}, },
addFonts: addFonts, addFonts: addFonts,
generatePDF,
} }
if (isModule) returnObj.generatePDF = generatePDF
return returnObj return returnObj
} }
......
This source diff could not be displayed because it is too large. You can view the blob instead.
...@@ -5,6 +5,7 @@ ...@@ -5,6 +5,7 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title> <title>Document</title>
<link rel="stylesheet" href="./assets/a-doc-editor.css"> <link rel="stylesheet" href="./assets/a-doc-editor.css">
<script src="./assets/jspdf.umd.min.js"></script>
<script src="./assets/a-doc-editor.js"></script> <script src="./assets/a-doc-editor.js"></script>
<style> <style>
......
...@@ -14,22 +14,23 @@ function setData() { ...@@ -14,22 +14,23 @@ function setData() {
} }
function generatePDF(){ function generatePDF(){
let url = `${window.origin}/pdf/generate` editor.generatePDF("your_doc.pdf")
let options = { // let url = `${window.origin}/pdf/generate`
method: 'POST', // let options = {
body: JSON.stringify( editor.getContent() ), // method: 'POST',
headers: { // body: JSON.stringify( editor.getContent() ),
'Content-Type': 'application/json', // headers: {
}, // 'Content-Type': 'application/json',
}; // },
fetch( url, options ) // };
.then( async (res)=>{ // fetch( url, options )
let parsedJson = await res.json() // .then( async (res)=>{
console.log('res', parsedJson) // let parsedJson = await res.json()
} ) // console.log('res', parsedJson)
.catch(err=>{ // } )
console.log(err) // .catch(err=>{
}) // console.log(err)
// })
} }
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment