Commit 68a69896 by ramdayalmunda

used pdf-lib library to generate text

parent daedde51
let isModule = (typeof module != 'undefined') ? true : false
var ADocEditor = function (customConfig) {
var fs, path;
var PDFDocument, rgb;
if (isModule) {
fs = require("fs");
path = require("path")
} else {
var { PDFDocument, rgb } = PDFLib
}
var styleTag;
var screenWidth = (typeof screen != 'undefined') ? screen.width : 1280
......@@ -32,7 +35,7 @@ var ADocEditor = function (customConfig) {
},
style: {
fontSize: 16,
fontFamily: 'customfont',
fontFamily: 'Kenia',
bold: false,
italic: false,
fontColor: "#001"
......@@ -54,10 +57,7 @@ var ADocEditor = function (customConfig) {
style: { ...config.style }
},
]
// // paragraphs // this line is added only for testing please remove this on completion
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
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":[]}]')
// // this is the combination of paragraph and list //
dataSet = [
{
id: ++counter, type: 0, style: { ...config.style }, formatedText: [],
......@@ -318,6 +318,7 @@ var ADocEditor = function (customConfig) {
`
addFonts(["./assets/fonts/customfont.woff", "./assets/fonts/customfont.ttf"], 'customfont')
addFonts(["./assets/fonts/Kenia-Regular.ttf"], 'Kenia')
container.innerHTML = htmlSetup
container.append(styleTag)
......@@ -810,7 +811,7 @@ var ADocEditor = function (customConfig) {
}
}
async function generatePDF(file) {
async function generatePDFJsPDF(file) {
const customFontDataURI = await getFontDataURI("./assets/fonts/customfont.ttf")
const { jsPDF } = jspdf;
......@@ -856,9 +857,9 @@ var ADocEditor = function (customConfig) {
...config.style,
...setData.style
}
doc.setFont( style.fontFamily )
doc.setFontSize( style.fontSize*3/2 )
doc.text( `${lines[l].listIndex + 1}.`, numberX, y)
doc.setFont(style.fontFamily)
doc.setFontSize(style.fontSize * 3 / 2)
doc.text(`${lines[l].listIndex + 1}.`, numberX, y)
}
}
......@@ -869,9 +870,9 @@ var ADocEditor = function (customConfig) {
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 )
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) {
......@@ -906,6 +907,105 @@ var ADocEditor = function (customConfig) {
}
}
async function generatePDF(file) {
// Create a new PDFDocument
const pdfDoc = await PDFDocument.create()
// register font-kit
pdfDoc.registerFontkit(fontkit)
let fontBytes = await new Promise( async ( res, rej )=>{
fetch( "./assets/fonts/Kenia-Regular.ttf" )
.then( async(data)=>{
res( await data.arrayBuffer() )
} ).catch((err)=>{
rej(err)
})
} )
const customFont = await pdfDoc.embedFont(fontBytes)
// Add a blank page to the document
let pageSetup = { width: config.pageSetup.canvasWidth, height: config.pageSetup.canvasHeight }
var page = pdfDoc.addPage([pageSetup.width, pageSetup.height])
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++
page = pdfDoc.addPage([pageSetup.width, pageSetup.height])
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
}
page.drawText( `${lines[l].listIndex + 1}.` , {
x: numberX,
y: config.pageSetup.canvasHeight-y,
size: style.fontSize*config.pageSetup.fontMultiplier,
font: customFont,
color: rgb(0, 0, 0),
})
}
}
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]
page.drawText( dataSet[lines[l].dataSetIndex].plainContent[c] , {
x: style.x,
y: config.pageSetup.canvasHeight-style.y,
size: style.fontSize*config.pageSetup.fontMultiplier,
font: customFont,
color: rgb(0, 0, 0),
})
setData.formatedText[c].x = x
setData.formatedText[c].y = y
if (setData.formatedText[c]?.width) {
x += setData.formatedText[c]?.width
}
}
}
}
const pdfBytes = await pdfDoc.save()
const blob = new Blob([pdfBytes], { type: "application/pdf" });
const downloadLink = document.createElement("a");
document.body.appendChild(downloadLink);
downloadLink.href = URL.createObjectURL(blob);
downloadLink.download = file; // Set desired filename
downloadLink.style.display = "none"; // Keep it hidden
downloadLink.click()
document.body.removeChild(downloadLink)
}
function addFonts(paths, name) {
if (!isModule) {
if (fontList.find(item => item.name.toLowerCase() == name.toLowerCase())) {
......
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
......@@ -5,6 +5,8 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="./assets/a-doc-editor.css">
<script src="./assets/fontkit.umd.min.js"></script>
<script src="./assets/pdf-lib.min.js" ></script>
<script src="./assets/jspdf.umd.min.js"></script>
<script src="./assets/a-doc-editor.js"></script>
......
var tempDocData = []
var editor = new ADocEditor({ element: document.getElementById("user-container-for-editor") })
console.log('editor', editor)
var extractedData = null
function extractData() {
......@@ -14,23 +13,7 @@ function setData() {
}
function generatePDF(){
editor.generatePDF("your_doc.pdf")
// let url = `${window.origin}/pdf/generate`
// let options = {
// method: 'POST',
// body: JSON.stringify( editor.getContent() ),
// headers: {
// 'Content-Type': 'application/json',
// },
// };
// fetch( url, options )
// .then( async (res)=>{
// let parsedJson = await res.json()
// console.log('res', parsedJson)
// } )
// .catch(err=>{
// console.log(err)
// })
editor.generatePDF("your_doc-pdf-lib.pdf")
}
......
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