createing PDF with pdfmake just writes the html on pdf - angularjs

I'm trying to create a pdf from my view created with angular. The problem is that the pdf looks like this:
Is it not able to work out the angular markup?
var docDefinition = { content: printHtml };
pdfMake.createPdf(docDefinition).download('optionalName.pdf');

Pdfmake is doing its work correctly, it is printing all the raw html to the pdf.
You want it to print in html but pdfmake doesn't work like this, by giving html code you can not generate a formatted pdf file, you will have to create a javascript object having document definition in it, this document definition contains your content and styles.
You can follow this link for basic example and check out some more complex examples here on github page of pdfmake.
Good Luck

// use npm package and initialise the pdfMake.
const pdfMake = require('pdfmake/build/pdfmake.js')
const pdfFonts = require('pdfmake/build/vfs_fonts.js')
pdfMake.vfs = pdfFonts.pdfMake.vfs
function showPDF() {
const statHeader = { text: data in header not the Header
header,bold: true}
const content = preparePDF(yourHTML)
const statFooter = 'data in footer not Footer footer, To add a
footer check the pdfMake documentation for footer.'
const name = ''
const docDefinition = {
// Add page count
footer: function (currentPage, pageCount) {
return {
margin: 10,
columns: [{ text: currentPage.toString() + ' of ' +
pageCount, alignment: 'center' }]
}
},
header: { text: name, style: 'gameName' },
content: [
statHeader,
content,
statFooter
],
styles: {
gameName: {
fontSize: 16,
bold: true,
alignment: 'left',
margin: [40, 20, 0, 80]
}
}
}
// creates pdf formated file with give name.
pdfMake.createPdf(docDefinition).download(`${name}.pdf`)
}
Wrap it in a function like
const htmlToPDF = require('html-to-pdfmake')
function preparePDF (yourHTML) {
let htmltoPDFData = []
const html = <div>yourHTML</div>
htmltoPDFData = htmlToPDF(html)
return htmltoPDFData
}

Related

Display HTML clusters with custom properties using react-map-gl (Mapbox)

I am trying to adapt the example Display HTML clusters with custom properties for react-map-gl.
I got basic clusters without custom styling working (adapted from Create and style clusters):
<ReactMapGL ref={mapRef}>
<Source id="poi-modal-geojson" type="geojson" data={pointsToGeoJSONFeatureCollection(points)}
cluster={true}
clusterMaxZoom={14}
clusterRadius={50}
>
<Layer {...{
id: 'clusters',
type: 'circle',
source: 'poi-modal-geojson',
filter: ['has', 'point_count'],
paint: {
'circle-color': [
'step',
['get', 'point_count'],
'#51bbd6',
100,
'#f1f075',
750,
'#f28cb1'
],
'circle-radius': [
'step',
['get', 'point_count'],
20,
100,
30,
750,
40
]
}
}} />
<Layer {...{
id: 'unclustered-point',
type: 'circle',
source: 'poi-modal-geojson',
filter: ['!', ['has', 'point_count']],
paint: {
'circle-color': '#11b4da',
'circle-radius': 4,
'circle-stroke-width': 1,
'circle-stroke-color': '#fff'
}
}} />
</Source>
</ReactMapGL>
Here, pointsToGeoJSONFeatureCollection(points: any[]): GeoJSON.FeatureCollection<GeoJSON.Geometry> is a function returning a GeoJSON (adapted from here).
However, I need more complex styling of markers and I am trying to adapt Display HTML clusters with custom properties without success so far. I mainly tried to adapt updateMarkers() and to call it inside useEffect():
const mapRef: React.Ref<MapRef> = React.createRef();
const markers: any = {};
let markersOnScreen: any = {};
useEffect(() => {
const map = mapRef.current.getMap();
function updateMarkers() {
const newMarkers: any = {};
const features = map.querySourceFeatures('poi-modal-geojson');
// for every cluster on the screen, create an HTML marker for it (if we didn't yet),
// and add it to the map if it's not there already
for (const feature of features) {
const coords = feature.geometry.coordinates;
const props = feature.properties;
if (!props.cluster) continue;
const id = props.cluster_id;
let marker = markers[id];
if (!marker) {
let markerProps = {
key: 'marker' + id,
longitude: coords[0],
latitude: coords[1],
className: 'mapboxgl-marker-start'
}
const el = React.createElement(Marker, markerProps, null),
marker = markers[id] = el;
}
newMarkers[id] = marker;
if (!markersOnScreen[id]) {
// TODO re-add
// marker.addTo(map);
}
}
// for every marker we've added previously, remove those that are no longer visible
for (const id in markersOnScreen) {
if (!newMarkers[id]) delete markersOnScreen[id];
}
markersOnScreen = newMarkers;
}
// after the GeoJSON data is loaded, update markers on the screen on every frame
map.on('render', () => {
if (!map.isSourceLoaded('poi-modal-geojson')) return;
updateMarkers();
});
}, [points]);
Unfortunately, the Marker created using React.createElement() isn't displayed I am not sure what is the right approach to create Marker elements in updateMarkers() or if my approach is completely wrong.
There is a great article on marker clustering which uses the supercluster and use-supercluster libraries and it makes clustering really easy not only for map box but for other map libraries as well, you can find it here.
You just have to convert your points into GeoJSON Feature objects in order to pass them to the useSupercluster hook and for the calculations to work. It will return an array of points and clusters depending on your current viewport, and you can map through it and display the elements accordingly based on the element.properties.cluster flag.
The properties property of the GeoJSON Feature object can be custom so you can pass whatever you need to display the markers later on when you get the final cluster array.

jsPdf html to pdf - text overflow cutting some of the last text (react)

I am trying to use jsPdf to generate a pdf from an html string.
I am able to generate pdf using the code below.
const generatePDF = () => {
const pdf = new jsPDF({
orientation: "p",
unit: "pt",
format: "a4",
});
const width = pdf.internal.pageSize.getWidth();
pdf
.html(htmlContent, {
width: width,
windowWidth: 794,
margin: [58, 80, 52, 80],
html2canvas: { scale: 0.57 },
})
.then(() => {
pdf.save('test.pdf');
});
};
However, i think the page break is now working as expected. in some pages, text is split between pages like this
[![enter code here][1]][1]
Anyone has a clue how to fix this?
You should probably use html2pdf instead of jspdf. It uses jspdf but is easier to use. Add a page break and it should be ok.

Adding a custom block at the end of the editor content in slatejs react

I have created an editor using Slate js in react.
I am trying to insert a block at the end of the editor content.
I came across a method to insert block at the range. How to specify the range of the document such that my custom blocks gets added at the end of the content but focus stays at the current selection and not at the end of the document.
function insertFile(editor, src, target) {
editor.insertBlock({
type: 'file',
data: { src },
})
}
My schema looks like this
const schema = {
blocks: {
file:{
isVoid: true
}
}
}
Using the Transforms object, it behaves just like you wished.
import { Transforms } from 'slate'
Transforms.insertNodes(
editor,
{ type: 'paragraph', children: [{ text: 'xxxx' }] },
{ at: [editor.children.length] }
)
To see the document for this: Link1 Link2

vis.js network: Edge colors not displaying in react.js app

I am having a problem with the edge colors when rendering a network visualisation through a react app.
I have a MindMapComponent which contains a network.
I receive the data for the network through the props for the component:
class MindMapComponent extends React.Component {
//React component to display a single submission Item.
//Displays the text and author of a Perspective Item
constructor(props) {
super(props);
this.state = {map: props.mindMap, node_options: props.node_options, edge_options: props.edge_options}
}
I then go ahead and create the network in my componentDidMount function:
componentDidMount(){
var edge_dataset = new vis.DataSet(JSON.parse(this.state.map.conceptmap_edges));
var nodes_dataset = new vis.DataSet(JSON.parse(this.state.map.conceptmap_nodes));
var data = {
nodes:nodes_dataset ,
edges: edge_dataset
};
var edge_options =JSON.parse(this.state.edge_options);
edge_options.color = {inherit:false};
var options = {
edges: edge_options,
nodes: JSON.parse(this.state.node_options),
physics: false,
locale: 'en',
interaction: {
navigationButtons: true,
keyboard: true,
hover: true
}
};
var network = new vis.Network(this.refs.network, data,options)
console.log(network);
}
And finally render the whole thing in my render function
render() {
const liStyle = {
borderStyle: 'outset',
backgroundColor: 'lightgrey',
marginBottom: '10px',
listStyleType: 'none'
};
const metaStyle = {
paddingLeft: '15px'
}
const networkStyle = {
height:'250px',
borderRight:'dashed 2px'
}
var dateString = new Date(this.state.map.date_added);
dateString = dateString.getDate() + "/" + (dateString.getMonth() +1) + "/" + dateString.getFullYear();
return <li key={this.state.map.id} style={liStyle}>
<div className = 'row'>
<div className = 'col-lg-8' ref = "network" style = {networkStyle}></div>
<div className = 'col-lg-4' style = {metaStyle}><br/><p>Submitted on: {dateString}</p></div>
</div>
</li>
}
The final network should look like this (rendered in normal html+js app).
However in my react app the colors of the edges do not display
I took a look inside of the network data structure (through the console.log(network) at the end of component did mount).
The body.data.edges part of the structure contains the correct color value. However the body.edge.[id].options.color part is empty
I believe this is the source of my problem but am not sure whether my analysis is correct or how to go about fixing it.
I think I have a solution (I ran into the same problem as you, but then in Angular2).
Try setting the color as an Object (see http://visjs.org/docs/network/edges.html) and specify the inherit property to false. E.g.(using typescript)
const myEdge: Edge = {
id: 'myEdge',
from: 'NODE1',
to: 'NODE2',
arrows: 'to',
color: {color: '#ff0000', inherit: false};
dashes: true
}
You might also want to set the highlight and hover colors

working bar charts/tables with sproutcore

I am currently working on a task which want to display bar charts/tables on the website.
The application is using: sproutcore (1.6) as front-end, Java Restful as backend.
However, I can't find some useful library for charts in sproutcore. Are there any ideas for that?
I search on the website, I feel the google chart tools is quite good, also jFreechart as backend is also a good choice.
I am not sure how to integrate that to sproutcore.
Thanks.
I'm using Flot to display charts on my Sproutcore app.
To use it, you need to create a flot directory inside the frameworks folder which will include the jquery.flot.js file (I've also include jquery.flot.pie.js file) and a core.js file with this content:
sc_require('jquery.flot.js');
sc_require('jquery.flot.pie.js');
Flot = SC.Object.create({
plot: $.plot
}) ;
Then, you need to add this new library to your buildfile :
config :yourapp,
:required => ['flot']
To display your charts in your app, you can use this custom view that I made to work with Flot:
GX.FlotView = SC.View.extend({
classNames: ['flot'],
//ex: [{ data: [[1326366000000, 1500], [1326452400000, 600]], label: 'title of the serie' }, ...]
data: [],
/*
ex: {
legend: { show: true },
series: line, points,
xaxis: { mode: "time", timeformat: "%d/%m/%y", }
grid: { backgroundColor: { colors: ["#FFF", "#fefefe"]}},
}
*/
options: [],
render: function(context, firstTime) {
var frame = this.get('frame'),
data = this.get('data'),
options = this.get('options');
// To avoid an error with flot, we check if width and height > 0
if(frame.width > 0 && frame.height > 0 && data && data.length) {
var layer = this.get('layer'),
plot = Flot.plot(layer, data, options);
}
},
viewDidResize: function() {
this.invokeLast(function() {
if (this.get('isVisibleInWindow')) this.set('layerNeedsUpdate', YES);
});
}.observes('data', 'data.[]'),
});
Then, you just have to bind the data and the option properties with your data.

Resources