I installed pdfkit and now I am trying to add text to pdf and save it to disk. I am following tutorial from http://blog.nodeknockout.com/post/9134350698/countdown-to-ko-8-introduction-to-pdfkit but I keep getting an error below. How can I add a text using node.js and pdfkit?
thank you.
source code:
doc = new PDFDocument();
doc.moveTo(300, 75)
.lineTo(373, 301)
.lineTo(181, 161)
.lineTo(419, 161)
.lineTo(227, 301)
.fill('red', 'even-odd');
var loremIpsum = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam in...';
doc.y = 320;
doc.fillColor('black')
.text(loremIpsum, {
paragraphGap: 10,
indent: 20,
align: 'justify',
columns: 2
});
doc.write('out.pdf');
error
/Users/sadmin/Dropbox/Node JS/wordlets/wordCloud.js:61
.text(loremIpsum, {
^
TypeError: Property 'text' of object [object PDFDocument] is not a function
at Object.createPDF (/Users/sadmin/Dropbox/Node JS/wordlets/wordCloud.js:61:5)
at /Users/sadmin/Dropbox/Node JS/wordlets/requestHandlers.js:62:15
at Request._callback (/Users/sadmin/Dropbox/Node JS/wordlets/wordCloud.js:116:5)
at Request.init.self.callback (/Users/sadmin/node_modules/request/main.js:122:22)
at Request.EventEmitter.emit (events.js:99:17)
at Request.<anonymous> (/Users/sadmin/node_modules/request/main.js:661:16)
at Request.EventEmitter.emit (events.js:126:20)
at IncomingMessage.Request.start.self.req.self.httpModule.request.buffer (/Users/sadmin/node_modules/request/main.js:623:14)
at IncomingMessage.EventEmitter.emit (events.js:126:20)
at IncomingMessage._emitEnd (http.js:366:10)
It should be doc.text since you have other lines of code between the .fill call and .text, creating a syntax error.
Related
I'm new to React and I hope somebody helps me understand how to solve this problem.
In my code below I'm retrieving product data from AliExpress's Dropshipping API; when I make the API call it returns an array with a set of information about 20 different products. from there, I want to use the map function to render a component that I've called "ProductCard" and pass the data points from the API call into the component as props. I believe this is what I've done in my code below, so when I check my app on a laptop or desktop device the code works as expected, but when I check my app on a mobile device the "ProductCard" component that the "productDisplay" function is responsible for creating dynamically does not render. What confuses me is that I only have this problem with small devices like mobile phones. Otherwise, my code works the way I want it to on larger devices like laptops or desktops. at first, I thought maybe there was something wrong with my phone, so I tried looking at it from other people's cell phones to see if the ProductCard component would render but it didn't.
I don't want to have to manually create the ProductCard components whenever I need to pull data from an API. so, can somebody please help me understand what I'm doing wrong and how to fix it? so that my ProductCard component can render properly on all devices, and can you please provide code examples in functional components instead of class components?
import SectionTitle from "../Base/SectionTitle";
import axios from "axios";
import Container from "react-bootstrap/Container";
import Row from "react-bootstrap/Row";
import Col from "react-bootstrap/Col";
import ProductCard from "./ProductCard";
function EcommerceMarket() {
const [aliExpressData, setAliExpressData] = useState();
useEffect(() => {
let pageIsMounted = true;
if (pageIsMounted) {
let url;
if (process.env.NODE_ENV === "production") {
url = `${process.env.REACT_APP_PRODUCTION_URL}/guest/e-commerce-service`;
} else {
url = `${process.env.REACT_APP_DEV_URL}/guest/e-commerce-service`;
}
const options = {
method: "GET",
url: url
};
axios
.request(options)
.then((response) => {
const marketData = response.data.content;
// console.log(marketData);
const filteredData = marketData.filter((product) => {
if (product.image) {
const targetProduct = product;
return targetProduct;
}
});
return filteredData;
})
.then((filteredData) => {
//console.log(filteredData);
setAliExpressData(filteredData);
})
.catch((error) => {
console.error(error);
});
}
return () => {
pageIsMounted = false;
};
}, []);
const productDisplay = () => {
if (aliExpressData) {
const updatedCards = aliExpressData.map((product) => {
const id = product.productId;
const productImage = product.image.imgUrl;
const productTitle = product.title.displayTitle;
const price = `$ ${product.prices.salePrice.minPrice}`;
return <ProductCard key={id} image={productImage} title={productTitle} productid={id} price={price} />;
});
return updatedCards;
}
};
return (
<div className="e-commerce">
<SectionTitle title="e-commerce market" />
<Container className="e-commerce__content-container" fluid>
<Row className="e-commerce__row">
<Col className="e-commerce__product-display" xs={{ span: 12, order: 2 }} lg={{ span: 8, order: 1 }}>
{productDisplay()}
</Col>
<Col className="e-commerce__service-explanation" xs={{ span: 12, order: 1 }} lg={{ span: 4, order: 2 }}>
<h2 className="e-commerce__service-explanation__title">service description</h2>
<p className="e-commerce__Product-description">
<span>Lorem ipsum dolor sit amet consectetur adipisicing elit. Quis optio sed reprehenderit officiis voluptatum fugiat quas iure facere voluptas repudiandae odio distinctio itaque animi omnis doloremque, delectus tempora. Nam, iste!</span>
<span>Molestias cupiditate itaque accusantium quisquam iusto placeat ipsa facere, molestiae perferendis, magni et? Deleniti quod illum id consectetur eius dolor nesciunt delectus recusandae modi, commodi ullam odit cumque sit maiores.</span>
</p>
<p className="e-commerce__Product-description">
<span>Lorem ipsum dolor sit, amet consectetur adipisicing elit. Veniam, earum autem unde dolore enim alias soluta cum harum at quibusdam, quam in perferendis distinctio ducimus libero quos impedit officiis itaque.</span>
<span>Necessitatibus vero sequi modi officia praesentium delectus quibusdam architecto quas unde. Inventore, officiis animi officia sit consequuntur accusamus omnis cupiditate assumenda voluptatum consequatur numquam accusantium! Quos nulla tenetur voluptatibus ipsum.</span>
</p>
<p className="e-commerce__Product-description">
<span>Lorem ipsum dolor sit amet consectetur adipisicing elit. Tenetur laboriosam maxime corrupti vitae nostrum, fugiat, iure, blanditiis harum exercitationem neque esse consectetur est quibusdam excepturi repudiandae mollitia voluptates qui repellendus?</span>
<span>Consequuntur necessitatibus, quidem sint, delectus expedita dolores dicta non modi est saepe distinctio debitis ut obcaecati animi omnis corrupti numquam! Quod iure quaerat, vero odit eveniet dolore ratione. Nam, laborum.</span>
</p>
</Col>
</Row>
</Container>
</div>
);
}
export default EcommerceMarket;
I have this simple well-formed html like
<span><p><b>User: </b>USERNAME<br><strong>Date: </strong>from 28-04-2022 08:00:00 to 28-04-2022 16:00:00<br><strong></p></span>
and I passed to qtip but once I show the tip I see it doesn't apply bold formatting...indeed saving into a normal html file it works well.... shall I have to add some particular option?
In the specific with this javascript :
$(info.el).qtip({
content: { text: $.ajax({url:"http://"+window.location.host+"/...../my.php?action=load_eventdetails&ID="+info.event.id, async:false}).responseText },
position: { target: 'mouse', effect: false, viewport: .... , adjust: { x: 10, y: 10, method: 'flipinvert' } },
});
I call a php to obtain an html string:
<html><body><p><span><b>User: </b>Name Surname<br><b>Date: </b>from 04-03-2016 08:00:00 to 04-03-2016 16:00:00<br><b>Room: </b>Room 1 ()<br><b>Placement: </b><br><b>Services:</b><br><ol style='list-style-type: circle'><li style='font-size: 13px'>n° 1 - Lorem Ipsum</li><li style='font-size: 13px'>n° 6 - Lorem Ipsum</li><li style='font-size: 13px'>n° 1 - Lorem Ipsum</li><li style='font-size: 13px'>n° 1 - Lorem Ipsum</li><li style='font-size: 13px'>n° 6 - Lorem Ipsum</li></ol><div style='font-size: 13px;margin-bottom: 1px'><div style='float:left'><b>Price:</b></div><div style='float:right'>€ XX,00</div></div><br><div style='font-size: 13px;margin-bottom: 5px'><div style='float:left'><b>Lorem Ipsum:</b></div><div style='float:right'>€ XX.00</div></div><br><div style='font-size: 13px;margin-bottom: 5px'><div style='float:left'><b>Lorem Ipsum:</b></div><div style='float:right'>€ XX.00</div></div><br><div style='font-size: 13px;margin-bottom: 1px'><div style='float:left'><b>Lorem Ipsum:</b></div><div style='float:right'>€ XX,XX</div></div><br> <div style="font-size: 13px;margin-bottom: 1px"><div style="float:left"><img src=".../images/myimg.png" /> <b>STATUS</b></div></div> </span></p></body></html>
Where with a simple html file I get correctly the result with bold formatting where expected...
Thanks in advance!
Cheers! :-)
I'm building a custom theme for a client and looks like I am going to have to create custom blocks and elements, but it has been a nightmare to understand how Shopware 6 works.
I copied the cms image element under my theme folder, following the directory structure that the documentation points. I did it that way to not miss any code or part I could forget or skip and then just added some new fields in it to kind of extend that new custom element. It kind of worked at the end, I also touched the twig and scss files and I could see at the frontend this new custom element. But then I tried to use the image element that comes with Shopware, but now looks like it is overriden by this new custom element I was trying to create.
Under ../custom/plugins/MyTheme/src/Resources/app/administration/src/module/sw-cms/elements/customElement/ the root index.js file which worked as I needed was:
import './component';
import './config';
import './preview';
Shopware.Service('cmsService').registerCmsElement({
name: 'image', // This is key I think but don't understand the relation.
label: 'Custom Element',
component: 'sw-cms-el-custom-element',
configComponent: 'sw-cms-el-config-custom-element',
previewComponent: 'sw-cms-el-preview-custom-element',
defaultConfig: {
media: {
source: 'static',
value: null,
required: true,
entity: {
name: 'media'
}
},
displayMode: {
source: 'static',
value: 'standard'
},
url: {
source: 'static',
value: null
},
newTab: {
source: 'static',
value: false
},
minHeight: {
source: 'static',
value: '340px'
},
verticalAlign: {
source: 'static',
value: null
},
cardColor: { // This is a new field I added
source: 'static',
value: 'true'
},
cardContent: { // This is a new field I added
source: 'static',
value: `
<h2>Lorem Ipsum dolor sit amet</h2>
<p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr,
sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat,
sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum.
Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.
Lorem ipsum dolor sit amet, consetetur sadipscing elitr,
sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.
At vero eos et accusam et justo duo dolores et ea rebum.
Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</p>
`.trim()
}
}
});
The code above makes my new custom element to work but then it overrides the image element entirely if I need to use that element somewhere else. I feel like the name: 'image' is the key here because then I replace it by another name let's say name: 'custom-element' and then the custom element didn't work at all, even though I copied the image element exactly as it is and just replaced it that name. The errors are related to the new fields I added, it says the values are undefined.
I have been reading some other people with the same issue and some guys talk about entities or resolvers but not sure how to follow that up.
Any advice would be appreciated. Thanks.
This error is popped up on a lambda when I've upgraded got npm module to 11.5.x from 9.6.0.
I'm using serverlessframework to develop and deploy micro services. Using Epsagon wrapper for better monitoring.
I've been struggling with this error from the past 3 days. Any help would be well appreciated.
AWS lambda runtime: Node 10.x
following are a few npm packages
"serverless-webpack": "^5.3.3",
"terser-webpack-plugin": "^4.1.0",
"webpack": "^4.44.1"
"epsagon": "^1.82.0",
"got": "^11.6.0", (with got 9.0.6, there is no issue)
While I can't paste the entire code snippet, following is a snippet. If I use the same code in a simple index.js file and run it then I cant reproduce this issue.
const { body } = await got(path, {
headers: { 'custom-key': customKey },
responseType: 'json',
method: 'POST',
json: { ts: i1599227703000 },
});
The following log snippet is from cloudWatch.
{
"errorType": "TypeError",
"errorMessage": "i is not a function",
"stack": [
"TypeError: i is not a function",
" at ClientRequest.patchedCallback (/opt/nodejs/node_modules/epsagon/dist/bundle.js:1:60626)",
" at Object.onceWrapper (events.js:286:20)",
" at ClientRequest.emit (events.js:203:15)",
" at ClientRequest.EventEmitter.emit (domain.js:448:20)",
" at ClientRequest.e.emit.f [as emit] (/var/task/epsagon_handlers/abcdNameChanged-epsagon.js:2:1080726)",
" at HTTPParser.parserOnIncomingClient [as onIncoming] (_http_client.js:565:21)",
" at HTTPParser.parserOnHeadersComplete (_http_common.js:111:17)",
" at TLSSocket.socketOnData (_http_client.js:451:20)",
" at TLSSocket.emit (events.js:198:13)",
" at TLSSocket.EventEmitter.emit (domain.js:448:20)"
]
}
Finally I could crack it.
If we enable epsagon auto-tracing thru epsagon webapp, it actually adds a layer called epsagon-node-layer to that lambda.
Disabling auto-tracing helped to not to get this error.
For more details, refer to: https://github.com/epsagon/epsagon-node/issues/295
It looks like in all the famo.us examples they use a really big lineHeight property to vertically align the text on a surface to the middle, whereas they use textAlign: "center" to align it horizontally. That seems problematic if there is no vertical align because if I want a paragraph of text the line height trick will screw that up.
Thanks!
This should be an easier question than it is but because of an issue with true-sizing surfaces, you may need to pull together a hack for this one.
The issue is that true-sized surfaces, cannot report their height to modifiers for properly calculating position at a given origin. You will have to set the actual height of the surface in order to achieve true centering.
In this example, The surface is centered in the entire context based on the size of the content. I subclassed the Surface so I could redefine deploy which takes the target element as the argument. I then set the size of the surface.state so that with its origin, it is able to center the element.
These are the types of issues that will be fixed soon, but a hack will have to do for now..
Here is the example.. Good Luck
var Engine = require('famous/core/Engine');
var Surface = require('famous/core/Surface');
var StateModifier = require('famous/modifiers/StateModifier');
function MySurface(options) {
Surface.apply(this, arguments);
this._superDeploy = Surface.prototype.deploy
}
MySurface.prototype = Object.create(Surface.prototype);
MySurface.prototype.constructor = MySurface;
MySurface.prototype.deploy = function deploy(target) {
this._superDeploy(target);
var size = this.getSize();
var width = size[0] == true ? target.offsetWidth : size[0] ;
var height = size[1] == true ? target.offsetHeight : size[1] ;
this.state.setSize([width,height]);
};
var context = Engine.createContext();
var lorem = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodoconsequat. Duis aute irure dolor in reprehenderit in voluptate velit essecillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";
var surface = new MySurface({
size: [200,true],
content: lorem,
properties: {
color: 'white',
textAlign: 'center',
backgroundColor: 'green'
}
});
surface.state = new StateModifier({origin:[0.5,0.5]});
context.add(surface.state).add(surface);