I want to convert to PDF a <div> that contains images using JS libraries locally, so I use the html2canvas library to convert from .png to base64 and jsPDF 1.5.2 from here, but when I tried opening the generated PDF on Adobe Acrobat it shows me the error 110: There was an error processing a page Ther was a problem reading this document, though it opened on the web browser (Chrome and Edge).
I looked for a solution and got this. It worked fine with v1.5.3, but then I found out that latest version was v2.5.1 on jsPDf GitHub repository and wanted to use it (latest the better... I think).
So I cloned it, used jspdf.es.min.js and ran into an issue: Uncaught TypeError: Failed to resolve module specifier "#babel/runtime/helpers/typeof". Relative references must start with either "/", "./", or "../". But there was no #babel folder.
I tried installing it with node.js npm install jspdf --save and solved that error (and other with fflate) by changing the import URL and referencing those files on the HTML file.
import _typeof from './../../#babel/runtime/helpers/typeof.js';
import { zlibSync, unzlibSync } from './../../fflate/lib/index.js';
or
import _typeof from './../../#babel/runtime/helpers/typeof.js';
import { zlibSync, unzlibSync } from './../../fflate/lib/index.d.ts';
Instead of
import _typeof from '#babel/runtime/helpers/typeof';
import { zlibSync, unzlibSync } from 'fflate;
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="viewport" content="width=device-width">
<title>pdf test</title>
<link href="style.css" rel="stylesheet" type="text/css" />
<script src="./html2pdf/html2canvas/html2canvas.min.js"></script>
</head>
<body>
<script type="module" src="./node_modules/jspdf/dist/jspdf.es.js"></script>
<script type="" src="./node_modules/fflate/lib/index.js" ></script>
<script type="" src="./node_modules/#babel/runtime/helpers/typeof.js"></script>
<div class="button-container">
<button id="createPDF" >Generate PDF</button>
</div>
<div id="toPrint" data-page="0">
<div >
<img src= "./image.png" >
</div>
<script type="module" src="./html2pdf.js"></script>
</div>
</body>
</html>
html2pdf.js
import sizes from './sizes.json' assert {type: 'json'};
import {jsPDF} from "./node_modules/jspdf/dist/jspdf.es.js"
document.getElementById("createPDF").addEventListener("click", () =>
{
let content = document.getElementById("toPrint");
console.table(sizes)
const page = Number(content.dataset.page)
console.log(page)
let title = document.getElementsByTagName("title")[0].text
let { PDFheight, PDFwidth} = sizes[page]
PDFheight = Number(PDFheight)
PDFwidth = Number(PDFwidth)
let doc = new jsPDF()
html2canvas(content).then((canvas) => {
let base64img = canvas.toDataURL("image/png")
console.log(base64img)
doc.addImage(base64img, 'PNG', 0, 0 , PDFwidth, PDFheight)
doc.save( title + ".pdf")
})
})
Also, I tried with jspdf.es.js and jspdf.umd.js. The thing is that when I solve those, other errors start to show up like:
Uncaught SyntaxError: The requested module './node_modules/jspdf/dist/jspdf.umd.js' does not provide an export named 'jsPDF' (at html2pdf.js:2:9) (html2pdf.js is my program)
Refused to execute script from 'http://127.0.0.1:5501/node_modules/fflate/lib/index.d.ts' because its MIME type ('video/mp2t') is not executable.
Uncaught ReferenceError: module is not defined at typeof.js:11:1
Uncaught ReferenceError: exports is not defined at index.js:6:1
Uncaught SyntaxError: The requested module './../../#babel/runtime/helpers/typeof.js' does not provide an export named 'default' (at jspdf.es.js:51:8)
I've tried including the CDN from cdnjs.com without success. I'm new to using JS libraries and want to gain experience working with GitHub and node.js How can I get started with this version of jsPDF?
Related
I am just trying to have fun with JS, I am creating a small project trying to implement a new architecture that I di not use before, I was always using js in React apps, or using native JS but not creating an app with it, I was using it to create some animations and handle some changes in my pages, nothing complex).
I want to learn how to create a JS app, implementing a MVC architecture ! I am not following any tutorial, so here is my folder structure :
Here is my index.html :
<html>
<head>
<title>Test js PROJECT</title>
</head>
<body>
<div id="root"></div>
<script src="app.js"></script>
</body>
</html>
And that's my app.js :
import { loadApp } from './MVC/controllers/loadApp';
loadApp();
And that's is my loadApp.js :
const loadApp = () => {
const showUsersOption = document.createElement('button');
const showProductsOption = document.createElement('button');
showUsersOption.createTextNode('Users');
showProductsOption.createTextNode('Products');
const app = document.getElementById('root');
app.appendChild(showUsersOption);
app.appendChild(showProductsOption);
}
export default loadApp;
So I think what I am trying to do is simple, adding two buttons to the root element, But I got this :
app.js:1 Uncaught SyntaxError: Cannot use import statement outside a
module
Based on this comment to the question, I added type module in my script like that :
<html>
<head>
<title>Test js PROJECT</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="app.js"></script>
</body>
</html>
But I got this :
Access to script at
'file:///C:/Users/Taoufiq.BENALLAH/Desktop/Master/js/app.js' from
origin 'null' has been blocked by CORS policy: Cross origin requests
are only supported for protocol schemes: http, data, chrome,
chrome-extension, chrome-untrusted, https.
GET file:///C:/Users/Taoufiq.BENALLAH/Desktop/Master/js/app.js
net::ERR_FAILED
Based on the comments in this question here, I have to restart my editor or run npm install, but I am not using node modules or anything, my app is simpler than that.
Any idea ? Any help would be much appreciated.
Hello,
I'm trying to create a simple PWA demo by following the steps of this article: "https://learn.microsoft.com/en-us/microsoft-edge/progressive-web-apps-chromium/get-started"
However when I reach the step to download and add the files: "pwabuilder-sw.js" and "pwabuilder-sw-register.js" to root and then add <script src="/pwabuilder-sw-register.js"></script> to the head of index.html I got error on Edge browser: "SCRIPT1086: SCRIPT1086: Module import or export statement unexpected here" I search around and I find that I have to add type="module" like this <script src="/pwabuilder-sw-register.js" type="module"></script> but now I'm getting another error: "0: Unable to get property 'define' of undefined or null reference" in
pwaupdate (175,5829)
My page code looks like:
Index.html
<html>
<head>
<title>Express</title>
<link rel="stylesheet" href="/stylesheets/style.css">
<link rel="manifest" href="/manifest.json">
<script src="/pwabuilder-sw-register.js" type="module"></script>
</head>
<body>
<h1>Express 2</h1>
<p>Welcome to Express</p>
</body>
</html>
pwabuilder-sw.js
// This is the service worker with the Cache-first network
const CACHE = "pwabuilder-precache";
importScripts('https://storage.googleapis.com/workbox-cdn/releases/5.0.0/workbox-sw.js');
self.addEventListener("message", (event) => {
if (event.data && event.data.type === "SKIP_WAITING") {
self.skipWaiting();
}
});
workbox.routing.registerRoute(
new RegExp('/*'),
new workbox.strategies.CacheFirst({
cacheName: CACHE
})
);
pwabuilder-sw-register.js
// This is the service worker with the Cache-first network
// Add this below content to your HTML page inside a <script type="module"></script> tag, or add the js file to your page at the very top to register service worker
import 'https://cdn.jsdelivr.net/npm/#pwabuilder/pwaupdate';
const el = document.createElement('pwa-update');
document.body.appendChild(el);
I searched a lot but I did not find any clue.
Please advise.
There are only 2 things you need to make this work:
Add pwabuilder-sw.js and pwabuilder-sw-register.js to your site root.
Add the following script tag to your <head>
<script type="module" src="pwabuilder-sw-register.js"></script>
Here's a quick sample that shows this working.
It looks like the MSDN article missed the "module" script type. My fault! I've updated the MSDN article to include this fix.
You normally don't need any more this script reference <script src="/pwabuilder-sw-register.js" type="module"></script>
The script will be loaded by the pwaupdate component. So simply add this code inside a block at the end of your HTML page:
import 'https://cdn.jsdelivr.net/npm/#pwabuilder/pwaupdate';
const el = document.createElement('pwa-update');
document.body.appendChild(el);
If it still doesn't work, please open an issue on our Github repo or ask to Justin who's in charge of this part on Twitter: https://twitter.com/Justinwillis96
Thanks!
David
The current solutions I know of for displaying JSCad Designs:
https://www.openjscad.org/
https://danmarshall.github.io/jscad-gallery/
https://risacher.org/OpenJsCad
https://johnwebbcole.gitlab.io/vesa-shelf/
https://joostn.github.io/OpenJsCad/
https://github.com/jscad/OpenJSCAD.org/blob/V2/packages/web/demo.html
all need quite some infrastructure to work.
https://www.openjscad.org/
is based on node The Userguide
https://www.openjscad.org/dokuwiki/doku.php?id=user_guide_website
states
The website can be integrated into an existing website.
But does not say how.
https://danmarshall.github.io/jscad-gallery/
Has it's sources at https://github.com/danmarshall/jscad-gallery. These were last modified in 2017 (some 2 years ago as of this post).
It use some dozen javascript files and jekyll to fulfill it's purpose.
Example: https://danmarshall.github.io/jscad-gallery/s-hook
The source code of a page is quite small:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>JSCAD Gallery s-hook</title>
<link rel="stylesheet" type="text/css" href="/jscad-gallery/site.css"/>
<script src='/jscad-gallery/browser_modules/#jscad/csg/0.3.7.js' type="text/javascript"></script>
<script src='/jscad-gallery/js/jscad-viewer.js' type="text/javascript"></script>
<script src='/jscad-gallery/js/ui.js' type="text/javascript"></script></head>
<body>
<h1>s-hook</h1>
<p>a simple S-hook design</p>
<div id="detail-viewer"></div>
<div id="inputs"></div>
<button onclick="detailView.export('stl', document.getElementById('download'))">Generate STL</button>
<div id="download"></div>
<script>
var design = {
title: "s-hook",
updated: null,
author: "Joost Nieuwenhuijse",
version: "1.0.0",
dependencies: [{"#jscad/scad-api":"^0.4.2"}],
image: "/browser_modules/s-hook/thumbnail.png",
camera: {"angle":{"x":-60,"y":0,"z":-45},"position":{"x":0,"y":0,"z":116}}
};
var detailView = new JscadGallery.DesignView();
detailView.load(document.getElementById('detail-viewer'), design, document.getElementById('inputs'));
</script>
<footer>
Jscad-gallery on GitHub
</footer>
</body>
</html>
I am looking for a (hopefully) simple solution that can be embedded in Mediawiki. For a start a plain html page with a bit of javascript would do for me.
see also:
https://openjscad.nodebb.com/topic/98/displaying-jscad-designs-in-media-wiki-or-plain-html-for-a-start
For a start I created http://wiki.bitplan.com/index.php/ParametricLampShade by simply copying the html from https://risacher.org/OpenJsCad/lampshadedemo.html.
I put the files:
csg.js
lightgl.js
openjscad.js
into the folder extensions/OpenJsCad.
With this simplistic approach i get the error:
Error in line 466: NetworkError: Failed to load worker script at http://wiki.bitplan.com/index.php/csg.js (nsresult = 0x804b001d)
The reasons seems to be in openjscad.js:
// callback: should be function(error, csg)
OpenJsCad.parseJsCadScriptASync = function(script, mainParameters, options, callback) {
var baselibraries = [
"csg.js",
"openjscad.js"
];
var baseurl = document.location.href.replace(/\?.*$/, '');
var openjscadurl = baseurl;
if (options['openJsCadPath'] != null) {
openjscadurl = OpenJsCad.makeAbsoluteUrl( options['openJsCadPath'], baseurl );
}
var libraries = [];
if (options['libraries'] != null) {
libraries = options['libraries'];
}
...
}
the openjscadurl is taken from the basepath which for Mediawiki is ../index.php.
How could I fix this?
What is the minimum set of javascript files needed and would be the proper versions of these files?
Changing the baseurl calculation to:
//alert(document.location);
var baseurl = document.location.href.replace(/index.php\/.*$/, 'extensions/OpenJsCad/');
//alert(baseurl);
fixed the issue.
See http://wiki.bitplan.com/index.php/ParametricLampShade for the result.
As a proof of concept
http://wiki.bitplan.com/index.php/Template:Jscad now has a Mediawiki Template.
I'd still like to learn about the javascript files and versions that should be used. Since the current approach use some outdated javascript files and can't even render the OpenJSCAD logo code from http://openjscad.org
The 1.10.0 version of https://www.npmjs.com/package/#jscad/web allows you to host a JsCad file with a single package. https://github.com/jscad/OpenJSCAD.org/pull/413
While this doesn't directly help you, I have a Vue component that allows you to show a JsCad file at https://gitlab.com/johnwebbcole/vue-openjscad
You may be able to use that to update your Mediawiki plugin.
J
I try to dynamically load a module on Firefox (version 66.0.2 (64 bits) on OS X 10.14.3) without success.
I get the following error:
SyntaxError: dynamic module import is not implemented
It works fine on Google Chrome.
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Dynamic module test</title>
<meta charset="utf-8">
</head>
<body>
<p>Test</p>
<script async="" type="module" src="module.js"></script>
<script type="module" src="main.js" ></script>
</body>
</html>
main.js:
let main = ()=> {
import('./module.js').then((loadedModule) => {
console.log('module loaded')
if(loadedModule.activate) {
loadedModule.activate()
}
})
.catch((error) => {
console.log(error)
});
}
document.addEventListener("DOMContentLoaded", main)
module.js:
export function activate() {
console.log('activate module')
}
I made a sample project that you can download export to .zip (File > Export to ZIP).
Since I had no answer so far, I made a bug report on bugzilla.
In Firefox, you can change preferences in about:config to load dynamic modules:
javascript.options.dynamicImport
As noted in comments, FF 67+ should address this problem. It also works with no changes if you use Firefox Developer Edition.
I'm new to LESS. I'm trying to compile less on the client side. I found an article that says to use the below script.
<script src="http://lesscss.googlecode.com/files/less-1.0.30.min.js">
</script>
But when I include it in my html (after the .less file) and open my local file in Chrome. The developer console says: http://lesscss.googlecode.com/files/less-1.0.30.min.js 404 (Not Found)
you can download the latest release from https://github.com/less/less.js/archive/v2.5.1.zip
or
https://raw.githubusercontent.com/less/less.js/master/dist/less.min.js
minified : https://raw.githubusercontent.com/less/less.js/master/dist/less.min.js
Updated
you have to use you own local server because some browsers will prevent .less serving from file:// protocol
To use your own server
Install Node
npm install http-server -g
then go to you folder using your console
http-server
now you can use http://localhost:8080 as your own server and .less will work
You want to compile on your local machine, then push the compiled file up to the server. And then you want to make sure that your CSS file references that compiled file.
The LESS docs recommend this java script to compile on your computer: http://lesscss.org/#download-options-browser-downloads
Or you can do the compile on client side approach, but you should update your script to use <script src="//cdnjs.cloudflare.com/ajax/libs/less.js/2.5.1/less.min.js"></script>, the CDN link from their site.
I'd still urge you to compile on your local machine, as this saves lots of precious time that your page would be without any styles. This article sums up other ways to go about a more robust build process.
Refer to the docs for usage. Download the less.js file and refer to it using <script src="less.js" type="text/javascript"></script>.
I made the example already mentioned using the link tag, but I also leave the example with the style tag that makes testing in development much easier.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- CSS -->
<!-- example with link tag -->
<link href="css/app.less" rel="stylesheet/less">
<!-- example with style tag -->
<style type="text/less">
html {
body {
background-color: red;
}
}
</style>
<!-- JS -->
<!-- The library automatically converts <link> tags -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/less.js/4.1.3/less.min.js"></script>
<!-- Convert style tags -->
<script>
const lessStyles = document.querySelectorAll('style[type="text/less"]')
lessStyles.forEach(styleElement => {
const lessCode = styleElement.innerText
less.render(lessCode, (error, output) => {
const cssCode = output.css
styleElement.innerText = cssCode
styleElement.setAttribute('type', 'text/css')
})
})
</script>
</head>
<body></body>
</html>
// Convert style tags
const lessStyles = document.querySelectorAll('style[type="text/less"]')
lessStyles.forEach(styleElement => {
const lessCode = styleElement.innerText
less.render(lessCode, (error, output) => {
const cssCode = output.css
styleElement.innerText = cssCode
styleElement.setAttribute('type', 'text/css')
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/less.js/4.1.3/less.min.js"></script>
<head>
<!-- example with link tag -->
<link href="css/app.less" rel="stylesheet/less">
<!-- example with style tag -->
<style type="text/less">
html {
body {
background-color: red;
}
}
</style>
</head>