How to use pdfjs-dist in vue cli typescript project? - node.js

I'm having issues getting pdfjs-dist working in a vue typescript cli project.
As soon as I try to use the pdfjs-dist I get this error
As far as I can guess it's an issue with my vue.config.js Or something else.
I'm struggling to progress past this point and haven't seen many examples with vue cli and webpack. There are some webpack rules people have posted, but I wasn't getting much progress on them.
Module parse failed: Unexpected token (2205:45)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| intent: renderingIntent,
| renderInteractiveForms: renderInteractiveForms === true,
> annotationStorage: annotationStorage?.serializable || null
| });
| }
Example
package.json
{
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"watch": "vue-cli-service build --mode development --watch"
},
"dependencies": {
"#types/pdfjs-dist": "^2.7.4",
"pdfjs-dist": "^2.8.335",
}
}
component
<template>
<div class="pdfviewer">
<canvas id="pdfPage"></canvas>
<div class="textLayer" id="text-layer"></div>
</div>
</template>
<script lang="ts">
import Vue from "vue";
import * as PDFJS from "pdfjs-dist";
export default Vue.extend({
name: "PdfViewer",
props: { pdfBase64: String },
methods: {
base64ToUint8Array(base64: string) {
const raw = atob(base64); // convert base 64 string to raw string
const uint8Array = new Uint8Array(raw.length);
for (let i = 0; i < raw.length; i++) {
uint8Array[i] = raw.charCodeAt(i);
}
return uint8Array;
},
async getPdf() {
const container = document.getElementById("pdfPage");
let pdfData = this.base64ToUint8Array(this.pdfBase64);
pdfData = pdfData.replace("data:application/pdf;base64,", "");
const loadingTask = PDFJS.getDocument(pdfData);
loadingTask.promise.then(function(pdf) {
const pageRetrieved = pdf.getPage(1);
pageRetrieved.then(function(page) {
const scale: any = 1;
const viewport = page.getViewport(scale);
const canvas = document.getElementById("pdfPage") as HTMLCanvasElement;
if (canvas) {
const context = canvas.getContext("2d");
canvas.height = viewport.height;
canvas.width = viewport.width;
page.render({ canvasContext: context as any, viewport: viewport });
}
});
})
}
},
mounted() {
// load pdf into canvas
this.getPdf()
}
});
</script>

Seems to be the only issue I had was the current version I was using "pdfjs-dist": "2.0.943" Seems to work just fine. I've now changed it to 2.3.200. Which is the most recent one working with this setting. Also text alignment works on this.
Notes on versions
Must change PDFJS.GlobalWorkerOptions.workerSrc ="https://cdn.jsdelivr.net/npm/pdfjs-dist#2.5.207/build/pdf.worker.min.js"; to match version imported
2.0.943 started at all the way to 2.3.200
2.5.207 won't fail to build, but fails to render the pdf in the canvas
2.7.570 onward fails to build w/ the error mentioned above. I suspect I need some webpack change in vue.config.js
I also had to add a watch
watch: {
src: function(newValue: string | null, oldValue: string | null) {
console.log("src update");
console.log(`Updating from`);
console.log(oldValue);
console.log(`to`);
console.log(newValue);
// TODO: if empty clear canvas
this.getPdf();
}
},
text layer
const txtLayer = document.getElementById(
"text-layer"
) as HTMLDivElement;
txtLayer.style.height = viewport.height + "px";
txtLayer.style.width = viewport.height + "px";
txtLayer.style.top = canvas.offsetTop + "px";
txtLayer.style.left = canvas.offsetLeft + "px";
page.render({
canvasContext: context as any,
viewport: viewport
});
page.getTextContent().then(function(textContent) {
console.log(textContent);
PDFJS.renderTextLayer({
textContent: textContent,
container: txtLayer,
viewport: viewport
});
});

Related

Using styled-jsx, How can I test style with enzyme?

I'm using Next.js with styled-jsx, testing enzyme + jest.
I want to test props style but I don't know How can I test.
index.js
const App = (props) => {
const { className, styles } = styles(props);
return (
<div className={`${className}`}>
<h1>test</h1>
{styles}
</div>
)
}
style.js
import css from 'styled-jsx/css';
export default (props) => css.resolve`
h1 {
color: ${props.color} || "red";
}
`
I tried to test this way but It's not working.
const wrapper = shallow(<App color={"blue"}/>);
expect(wrapper.find('h1').prop('style')).toHaveProperty('color', 'blue');
Is there way to solve this problem?
Using react-test-renderer npm package you can do snapshot testing for Style component. Try this, might help you:
import renderer from 'react-test-renderer';
test('Style component unit testing', () => {
const tree = renderer.create(<App color={"blue"} />).toJSON()
expect(tree).toMatchSnapshot()
expect(tree).toHaveStyleRule('color', 'red')
})

React + Material-UI - Warning: Prop className did not match

I'm having difficulty with differences between client-side and server-side rendering of styles in Material-UI components due to classNames being assigned differently.
The classNames are assigned correctly on first loading the page, but after refreshing the page, the classNames no longer match so the component loses its styling. This is the error message I am receiving on the Console:
Warning: Prop className did not match.
Server: "MuiFormControl-root-3 MuiFormControl-marginNormal-4
SearchBar-textField-31"
Client: "MuiFormControl-root-3 MuiFormControl-marginNormal-4
SearchBar-textField-2"
I've followed the Material-UI TextField example docs, and their accompanying Code Sandbox example, but I can't seem to figure out what is causing the difference between the server and client classNames.
I experienced a similar issue when adding Material-UI Chips with a delete 'x' icon. The 'x' icon rendered with a monstrous 1024px width after refreshing. The same underlying issue being that icon was not receiving the correct class for styling.
There are a few questions on Stack Overflow addressing why the client and server might render classNames differently (e.g. need to upgrade to #Material-UI/core version ^1.0.0, using a custom server.js, and using Math.random in setState), but none of these apply in my case.
I don't know enough to tell whether this Github discussion might help, but likely not since they were using a beta version of Material-UI.
Minimal steps to reproduce:
Create project folder and start Node server:
mkdir app
cd app
npm init -y
npm install react react-dom next #material-ui/core
npm run dev
edit package.json:
Add to 'scripts': "dev": "next",
app/pages/index.jsx:
import Head from "next/head"
import CssBaseline from "#material-ui/core/CssBaseline"
import SearchBar from "../components/SearchBar"
const Index = () => (
<React.Fragment>
<Head>
<link
rel="stylesheet"
href="https://fonts.googleapis.com/css?family=Roboto:300,400,500"
/>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta charSet="utf-8" />
</Head>
<CssBaseline />
<SearchBar />
</React.Fragment>
)
export default Index
app/components/SearchBar.jsx:
import PropTypes from "prop-types"
import { withStyles } from "#material-ui/core/styles"
import TextField from "#material-ui/core/TextField"
const styles = (theme) => ({
container: {
display: "flex",
flexWrap: "wrap",
},
textField: {
margin: theme.spacing.unit / 2,
width: 200,
border: "2px solid red",
},
})
class SearchBar extends React.Component {
constructor(props) {
super(props)
this.state = { value: "" }
this.handleChange = this.handleChange.bind(this)
this.handleSubmit = this.handleSubmit.bind(this)
}
handleChange(event) {
this.setState({ value: event.target.value })
}
handleSubmit(event) {
event.preventDefault()
}
render() {
const { classes } = this.props
return (
<form
className={classes.container}
noValidate
autoComplete="off"
onSubmit={this.handleSubmit}
>
<TextField
id="search"
label="Search"
type="search"
placeholder="Search..."
className={classes.textField}
value={this.state.value}
onChange={this.handleChange}
margin="normal"
/>
</form>
)
}
}
SearchBar.propTypes = {
classes: PropTypes.object.isRequired,
}
export default withStyles(styles)(SearchBar)
Visit page in browser localhost:3000 and see this:
red border around TextField component
Refresh the browser and see this:
TextField component's styles are gone
Notice that the red border around TextField disappears.
Relevant Libs:
"react": 16.4.0
"react-dom": 16.4.0
"next": 6.0.3
"#material-ui/core": 1.2.0
The problem is the SSR rendering in Next.js, which produces the style fragment before the page is rendered.
Using Material UI and Next.js (as the author is using), adding a file called _document.js solved the problem.
Adjusted _document.js (as suggested here):
import React from 'react';
import Document, { Html, Head, Main, NextScript } from 'next/document';
import { ServerStyleSheets } from '#material-ui/styles'; // works with #material-ui/core/styles, if you prefer to use it.
import theme from '../src/theme'; // Adjust here as well
export default class MyDocument extends Document {
render() {
return (
<Html lang="en">
<Head>
{/* Not exactly required, but this is the PWA primary color */}
<meta name="theme-color" content={theme.palette.primary.main} />
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
}
// `getInitialProps` belongs to `_document` (instead of `_app`),
// it's compatible with server-side generation (SSG).
MyDocument.getInitialProps = async (ctx) => {
// Resolution order
//
// On the server:
// 1. app.getInitialProps
// 2. page.getInitialProps
// 3. document.getInitialProps
// 4. app.render
// 5. page.render
// 6. document.render
//
// On the server with error:
// 1. document.getInitialProps
// 2. app.render
// 3. page.render
// 4. document.render
//
// On the client
// 1. app.getInitialProps
// 2. page.getInitialProps
// 3. app.render
// 4. page.render
// Render app and page and get the context of the page with collected side effects.
const sheets = new ServerStyleSheets();
const originalRenderPage = ctx.renderPage;
ctx.renderPage = () =>
originalRenderPage({
enhanceApp: (App) => (props) => sheets.collect(<App {...props} />),
});
const initialProps = await Document.getInitialProps(ctx);
return {
...initialProps,
// Styles fragment is rendered after the app and page rendering finish.
styles: [...React.Children.toArray(initialProps.styles), sheets.getStyleElement()],
};
};
This problem is related to MUI using dynamic class name which contain an ID. The IDs from the server side rendered CSS are not the same as the client side CSS, hence the mismatch error. A good start is to read the MUI SSR documentation
If you have this problem with nextjs (as I did) follow the example provided by the MUI team, which can be found here: material-ui/examples/nextjs
The most important part is in "examples/nextjs/pages/_app.js":
componentDidMount() {
// Remove the server-side injected CSS.
const jssStyles = document.querySelector('#jss-server-side');
if (jssStyles) {
jssStyles.parentElement.removeChild(jssStyles);
}
}
the related ticket can be found here: mui-org/material-ui/issues/15073
what it does, is remove the server side rendered stylesheet and replace it by a new client side rendered one
The issue is the server side generates the class names but style sheets are not automatically included in the HTML. You need to explicitly extract the CSS and append it to the UI for the server side rendered components. The whole process is explained here: https://material-ui.com/guides/server-rendering/
There is one other important, separate issue here: Material UI V4 is not React Strict Mode compatible. Strict mode compatibility is slated for version 5 with the adoption of the Emotion style engine.
Until then, be sure you disable React Strict Mode. If you're using Next.js, this is turned on by default if you've created your app using create-next-app.
// next.config.js
module.exports = {
reactStrictMode: false, // or remove this line completely
}
I had the same problem with Next.js and styled component, with the transpilation by Babel. Actually, the class names are different on the client and the server side.
Fix it in writing this in your .babelrc :
{
"presets": ["next/babel"],
"plugins": [
[
"styled-components",
{ "ssr": true, "displayName": true, "preprocess": false }
]
]
}
I met this problem on Material-ui V5. The solution to fix this problem is to make sure that class name generator needs to behave identically on the server and on the client.
so adding the code below in your _app.js:
import { StylesProvider, createGenerateClassName } from '#mui/styles';
const generateClassName = createGenerateClassName({
productionPrefix: 'c',
});
export default function MyApp(props) {
return <StylesProvider generateClassName={generateClassName}>...</StylesProvider>;
}
// 1 . Warning: prop classname did not match. Material ui with React Next.js
// 2 . Use your customization css here
const useStyles = makeStyles((theme) => ({
root: {
flexGrow: 1,
},
title: {
flexGrow: 1,
},
my_examle_classssss: {
with: "100%"
}
}));
// 3 . Here my Component
const My_Example_Function = () => {
const classes = useStyles();
return (
<div className={classes.root}>
<Container>
<Examle_Component> {/* !!! Examle_Component --> MuiExamle_Component*/}
</Examle_Component>
</Container>
</div>
);
}
export default My_Example_Function
// 4. Add name parameter to the makeStyles function
const useStyles = makeStyles((theme) => ({
root: {
flexGrow: 1,
},
title: {
flexGrow: 1,
},
my_examle_classssss: {
with: "100%"
},
}), { name: "MuiExamle_ComponentiAppBar" });
{/* this is the parameter you need to add { name: "MuiExamle_ComponentiAppBar" } */ }
{/* The problem will probably be resolved if the name parameter matches the first className in the Warning: you recive..
EXAMPLE :
Warning: Prop `className` did not match.
Server: "MuiSvgIcon-root makeStyles-root-98"
Client: "MuiSvgIcon-root makeStyles-root-1"
The name parameter will be like this { name: "MuiSvgIcon" }
*/ }
I like to share this mismatching case:
next-dev.js?3515:32 Warning: Prop className did not match. Server:
"MuiButtonBase-root MuiIconButton-root PrivateSwitchBase-root-12
MuiSwitch-switchBase MuiSwitch-colorSecondary" Client:
"MuiButtonBase-root MuiIconButton-root PrivateSwitchBase-root-12
MuiSwitch-switchBase MuiSwitch-colorSecondary
PrivateSwitchBase-checked-13 Mui-checked"
On client there are two more classes which means that the behavior on client-side is different. In this case, this component shouldn't render on server-side. The solution is to dynamically render this component:
export default dynamic(() => Promise.resolve(TheComponent), { ssr: false });
I had a problem with different classNames for client and server. I was using React, Material-UI, makeStyles and SSR (server-side rendering).
The error was:
Warning: Prop `className` did not match. Server: "jss3" Client: "App-colNav-3"
I spent several hours before I figured out that I had discrepancy in webpack mode for client and server. The scripts in package.json were:
"devServer": "webpack --config webpack.server.config.js --mode=production --watch",
"devClient": "webpack --mode=development --watch",
After I changed both to have development mode, the problem was solved :)
"devServer": "webpack --config webpack.server.config.js --mode=development --watch",
"devClient": "webpack --mode=development --watch",
If somebody is still struggling even after trying above solutions, Try this
If you have used noSsr prop in any of your components or theme, then remove it.
I had the following config in mui theme object, which was causing this problem.
import { createTheme, responsiveFontSizes } from "#mui/material/styles";
let theme = createTheme({
components: {
MuiUseMediaQuery: {
defaultProps: {
noSsr: true,
},
},
},
palette: {
mode: "light",
common: {
black: "#000",
white: "#fff",
},
primary: {
main: "#131921",
contrastText: "#fff",
},
secondary: {
main: "#fb6a02",
contrastText: "#fff",
}
}
})
RemovingnoSSr fixed all of the issues in my app including style mismatch between client and server.
The problem is cause by Nextjs server side rendering. In order to solve I do as following:
Make a component to detect whether is it from Client side
import { useState, useEffect } from "react";
interface ClientOnlyProps {}
// #ts-ignore
const ClientOnly = ({ children }) => {
const [mounted, setMounted] = useState<boolean>(false);
useEffect(() => {
setMounted(true);
}, []);
return mounted ? children : null;
};
export default ClientOnly;
Wrap my page component using ClientOnly component
export default function App() {
return (
<ClientOnly>
<MyOwnPageComponent>
</ClientOnly>
);
}
So the idea is, if it is client side then only render the component on the page. Therefore if current rendering is from Client side, render <MyOwnPageComponent>, else render nothing
In my case the issue happened because of different compilation modes of webpack for client-side code and server-side: client's bundle was generated by webpack using "production" mode, while server ran some SSR code from a package optimized for "development". This created a different "className" hash in styled-components in generateAndInjectStyles():
if (process.env.NODE_ENV !== 'production') dynamicHash = phash(dynamicHash, partRule + i);
So my fix was just to align the webpack modes.
You can add the name in anywhere you use makeStyles, like this:
const useStyles = makeStyles({
card: {
backgroundColor: "#f7f7f7",
width: "33%",
},
title: {
color: "#0ab5db",
fontWeight: "bold",
},
description: {
fontSize: "1em"
}
}, { name: "MuiExample_Component" });
I am not sure how it works, but I found it here: Warning: Prop `className` did not match ~ Material UI css arbitrarily breaks on reload
I'm also using NextJS + MUI v5 and I ran into this exact error right after merging Git branches. I suspect the merge corrupted something in the cache. I deleted the contents of .next/ and restarted the dev server and the error went away.
#Leonel Sanches da Silva's answer didn't work for me, as #material-ui/styles is deprecated, but using a snippet I found for another (non-material UI) project seems to have worked just fine for me:
Hat tip to Raul Sanchez on dev.to for the answer to this one.
Next doesn't fetch styled-components styles on the server, to do that you need to add this page to pages/_document.js:
import Document from 'next/document'
import { ServerStyleSheet } from 'styled-components'
export default class MyDocument extends Document {
static async getInitialProps(ctx) {
const sheet = new ServerStyleSheet()
const originalRenderPage = ctx.renderPage
try {
ctx.renderPage = () =>
originalRenderPage({
enhanceApp: (App) => (props) =>
sheet.collectStyles(<App {...props} />),
})
const initialProps = await Document.getInitialProps(ctx)
return {
...initialProps,
styles: (
<>
{initialProps.styles}
{sheet.getStyleElement()}
</>
),
}
} finally {
sheet.seal()
}
}
}
This code may update, so check Next's styled-components example for the latest.

Typescript compiles `tsx` to a wrong type of modue

I'm trying to use Typescript together with Node and React. However I'm struggling to set up the Typescript compiler to use the correct type of the “module convention”. I know that ES6 modules do work correctly, but Typescript always generates a non-standard module syntax that, for some reason, just doesn't work.
.
If I save this code into a .js file, it works correctly:
import React, { Component } from 'react';
import './App.css';
let logo = require('./logo.svg');
class App extends Component {
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Welcome to React</h1>
</header>
<p className="App-intro">
To get started, edit <code>src/App.js</code> and save to reload.
</p>
<p>{logo}</p>
</div>
);
}
}
export default App;
However, if I save it to a .tsx file, it compiles to this:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const react_1 = require("react");
require("./App.css");
let logo = require('./logo.svg');
class App extends react_1.Component {
render() {
return (react_1.default.createElement("div", { className: "App" },
react_1.default.createElement("header", { className: "App-header" },
react_1.default.createElement("img", { src: logo, className: "App-logo", alt: "logo" }),
react_1.default.createElement("h1", { className: "App-title" }, "Welcome to React")),
react_1.default.createElement("p", { className: "App-intro" },
"To get started, edit ",
react_1.default.createElement("code", null, "src/App.js"),
" and save to reload."),
react_1.default.createElement("p", null, logo)));
}
}
exports.default = App;
Which results in a Node error react_1.default is undefined. I tried adding a esModuleInterop flag to the Typescript compiler, which added this definition:
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
}
and changed require("react") to __importDefault(require("react")). That fixes the first problem, however react_1.Component is still undefined. Is there a way to set the Typescript compiler to use the standard ES6 modules?
Add this to tsconfig.json:
"compilerOptions": {
"module": "es6"
}

Setting iframe height to scrollHeight in ReactJS using IframeResizer

The typical solution to the problem doesn't work in in React due to its dynamically generated component structure and event model, as opposed to traditional static HTML. I tried with react-iframe-resizer-super but not found perfect solution.
My code:
import React, {PropTypes} from 'react';
import ReactIframeResizer from 'react-iframe-resizer-super';
class Frame extends React.Component {
constructor() {
super();
}
componentDidUpdate() {
const iframeResizerOptions = {
// log: true,
// autoResize: true,
checkOrigin: false,
// resizeFrom: 'parent',
// heightCalculationMethod: 'max',
// initCallback: () => { console.log('ready!'); },
// resizedCallback: () => { console.log('resized!'); },
};
}
render() {
return (
<div style={{position: 'relative'}}>
<IframeResizer iframeResizerOptions={iframeResizerOptions}>
<iframe scrolling="no" src="https://en.wikipedia.org/wiki/Main_Page" allowfullscreen
style={{width:'100%', height:'100%'}}
}}></iframe>
</IframeResizer>
</div>
);
}
}
Then I got following error:
Uncaught ReferenceError: IframeResizer is not defined
Is there a way in React to set the height of an iframe to the height of its scrollable contents or is there any alternative way to archive this requirement?
I refer following link:
https://www.npmjs.com/package/react-iframe-resizer-super
This question is long decease, but I thought I would add just in case anyone else looking for clarification on using react-iframe-resizer-super + iframe-resizer (JS)
The problem in the code above is a misspelling of the imported component.
import ReactIframeResizer from 'react-iframe-resizer-super';
Should be:
import IframeResizer from 'react-iframe-resizer-super';
As you've used it inside your Frame component.
For those looking for clarification on using the library, here is my dead simple working solution:
Install dependencies on React project containing iFrame yarn add react-iframe-resizer-super iframe-resizer
Include iframeResizer.contentWindow.min.js on the page that you are using as the source of your iFrame.
Usage in React:
DynamicIFrame.jsx
import React from 'react';
import IframeResizer from 'react-iframe-resizer-super';
export const DynamicIFrame = props => {
const { src } = props;
const iframeResizerOptions = {
log: true,
// autoResize: true,
checkOrigin: false,
// resizeFrom: 'parent',
// heightCalculationMethod: 'max',
// initCallback: () => { console.log('ready!'); },
// resizedCallback: () => { console.log('resized!'); },
};
return (
<IframeResizer src={src} iframeResizerOptions={iframeResizerOptions} />
);
};

can't test ember component that appends a div to the dom

I have a ember-cli-addon that adds a component which appends a div with a specific class to the consuming application. I'm trying to test this integration and having difficulty to setup the test.
I have tried to unit test the component as well but that doesn't work quite as expected. Here's what I've tried:
I've copied the component from my addon directory to tests/dummy/components/jquery-backstretch.js to make it available to the dummy test application:
jquery-backstretch.js
import Ember from 'ember';
export default Ember.Component.extend({
tagName: 'jquery-backstretch',
image: null,
selector: 'body',
fade: 0,
duration: 5000,
centeredX: true,
centeredY: true,
setupJquerybackstretch: function() {
var image = this.get('image');
if (! Ember.isEmpty(image)) {
var options = {
fade: this.get('fade'),
centeredX: this.get('centeredX'),
centeredY: this.get('centeredY')
};
var jqbsImage;
if (Ember.typeOf(image) === 'string') {
jqbsImage = 'assets/' + image;
} else if (Ember.isArray(image)) {
options.duration = this.get('duration');
jqbsImage = image.map(function(img) {return 'assets/' + img;});
} else {
Ember.Logger.error('Ember JQuery-Backstretch: Unsupported "image" format.');
}
Ember.$(this.get('selector')).backstretch(jqbsImage, options);
} else {
Ember.Logger.error('Ember JQuery-Backstretch: image not supplied.');
}
}.on('didInsertElement'),
teardownJquerybackstretch: function() {
Ember.$(this.get('selector')).backstretch('destroy');
}.on('willDestroyElement')
});
this causes the component to append the img to the body of the test page and not to #ember-testing-container, changing the selector to #ember-testingn-container puts the img in the right place but the test can't find it:
tests/acceptance/jquery-backstretch.js
import Ember from 'ember';
import {
module,
test
} from 'qunit';
import startApp from '../../tests/helpers/start-app';
var application;
module('Acceptance: JqueryBackstretch', {
beforeEach: function() {
application = startApp();
},
afterEach: function() {
// Ember.run(application, 'destroy');
}
});
test('backstretch added to body tag', function(assert) {
visit('/');
andThen(function() {
assert.equal(find('.backstretch > img').length, 1, 'Backstretch found');
});
});
application.hbs
<h2 id="title">Welcome to Ember.js</h2>
{{jquery-backstretch image="img/emberjs.png"}}
{{outlet}}
the test is not passing, it can't find the image, I also tried to test the component and append it to the DOM then test to see if it's in the DOM but that didn't yield better results.
How can I test this please?

Resources