From fefa45a5cde6b8baa043201e193cc8b2a2d03fff Mon Sep 17 00:00:00 2001
From: DanMHammer <35697323+DanMHammer@users.noreply.github.com>
Date: Thu, 22 Jul 2021 12:19:44 -0500
Subject: [PATCH] Return a print function from usePDF
---
README.md | 20 ++++++++++++++++++++
packages/renderer/src/dom.js | 30 +++++++++++++++++++++++++++++-
2 files changed, 49 insertions(+), 1 deletion(-)
diff --git a/README.md b/README.md
index e50badc55..fa516d040 100644
--- a/README.md
+++ b/README.md
@@ -78,6 +78,26 @@ const App = () => (
ReactDOM.render(, 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: })
+
+ return (
+
+ )
+);
+
+ReactDOM.render(, document.getElementById('root'));
+```
+
+
### `Node.` Save in a file
```jsx
import React from 'react';
diff --git a/packages/renderer/src/dom.js b/packages/renderer/src/dom.js
index 9d4346b51..0b4737ed0 100644
--- a/packages/renderer/src/dom.js
+++ b/packages/renderer/src/dom.js
@@ -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 }) => {