Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Return a print function from usePDF #1420

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,26 @@ const App = () => (
ReactDOM.render(<App />, document.getElementById('root'));
```

### `Web.` usePDF
```jsx
import React from 'react';
import ReactDOM from 'react-dom';
import { usePdf, PDFViewer} from '@react-pdf/renderer';

import MyDocument from ...;

const App = () => (
const [instance, update, print] = usePDF({document: <MyDocument />})

return (
<button type="button" onClick={() => print()}>Print</button>
)
);

ReactDOM.render(<App />, document.getElementById('root'));
```


### `Node.` Save in a file
```jsx
import React from 'react';
Expand Down
30 changes: 29 additions & 1 deletion packages/renderer/src/dom.js
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,35 @@ export const usePDF = ({ document }) => {
pdfInstance.current.updateContainer(document);
};

return [state, update];
const print = () =>
new Promise((resolve, reject) => {
try {
// Create a hidden iframe
const iframe = window.document.createElement(`iframe`);
iframe.style.display = `none`;

// Assign url to iframe
iframe.src = state.url;

iframe.addEventListener(`load`, () => {
// Remove the iframe once focus returns to the main window
window.addEventListener(`focus`, () => {
iframe.remove();
});

iframe.focus();
iframe.contentWindow.print();
});

window.document.body.appendChild(iframe);

resolve(true);
} catch (error) {
reject(error);
}
});

return [state, update, print];
};

export const BlobProvider = ({ document: doc, children }) => {
Expand Down