Skip to content

Commit

Permalink
impelementation pagedjs with nextjs
Browse files Browse the repository at this point in the history
  • Loading branch information
Edikustriyadi committed May 9, 2023
1 parent 0d6ab5d commit 56ead17
Show file tree
Hide file tree
Showing 3 changed files with 144 additions and 57 deletions.
2 changes: 1 addition & 1 deletion pages/_app.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { AnimatePresence } from "framer-motion";
import { CurrentSlideProvider } from "../context/CurrentSlideContext";
import { ModeProvider } from "../context/ModeContext";
import TransitionPage from "../layouts/TransitionPage";
// import '../styles/pdf.css'
import '../styles/pdf.css'



Expand Down
113 changes: 57 additions & 56 deletions pages/files/[format]/[file].js
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,14 @@ import remarkUnwrapImages from 'remark-unwrap-images';
import { theme } from '../../../constants/theme';
import fs from 'fs'
import path from 'path'

import pageStyle from './pdf.module.css'
import Head from 'next/head';
import Script from 'next/script';

const glob = require('glob')


function removeSection(pad, tagName) {
const re = new RegExp("<" + tagName + "\\s+[^>]*>(.*?)</" + tagName + ">", "gs");
const re = new RegExp("<" + tagName + "\\s+[^>]*>(.*?)</" + tagName + ">", "gs");
return (pad.replace(re, ""));
}

Expand All @@ -30,7 +30,7 @@ export async function getStaticPaths() {
const targetDir = path.join(process.cwd(), 'markdown', '/')
// grab all markdown files
const docPaths = glob.sync(path.join(targetDir, '**/*.{md,mdx}'))

docPaths.forEach(element => {
paths.push({
params: {
Expand Down Expand Up @@ -59,7 +59,7 @@ export async function getStaticPaths() {
}

export async function getStaticProps(context) {

const MDXoptions = {
remarkPlugins: [remarkGfm, remarkUnwrapImages],
format: 'mdx',
Expand All @@ -82,10 +82,10 @@ export async function getStaticProps(context) {
if (context.params.format === 'ppt') {
pad = '<SlidePage>\n' + pad + '\n</SlidePage>'
} else if (context.params.format === 'pdf') {
pad = '<div>'+pad+'</div>'
pad = '<div>' + pad + '</div>'
} else {
pad = removeSection(pad, 'TitleSlide');
pad = '<MDXViewer>\n' + pad.replace('---','') + '\n</MDXViewer>'
pad = '<MDXViewer>\n' + pad.replace('---', '') + '\n</MDXViewer>'
}
} catch (error) {
console.log(error)
Expand All @@ -103,7 +103,7 @@ export async function getStaticProps(context) {
</SlidePage>
`;

mdxSource = await serialize(pad ?? error_message, { scope: {}, mdxOptions : { ...MDXoptions}, parseFrontmatter: true } )
mdxSource = await serialize(pad ?? error_message, { scope: {}, mdxOptions: { ...MDXoptions }, parseFrontmatter: true })

} catch (error) {
const error_message = `
Expand All @@ -114,69 +114,70 @@ export async function getStaticProps(context) {
</SlidePage>
`
console.log('serialize error : ', error)
mdxSource = await serialize(error_message, { scope: {}, mdxOptions : { ...MDXoptions}, parseFrontmatter: true } )
mdxSource = await serialize(error_message, { scope: {}, mdxOptions: { ...MDXoptions }, parseFrontmatter: true })
}

return {
props: {
source: mdxSource,
file: context.params.file,
format: context.params.format
}
return {
props: {
source: mdxSource,
file: context.params.file,
format: context.params.format
}
}
}

export default function Pad({source, format}) {
const [hydrated, setHydrated] = useState(false);
export default function Pad({ source, format }) {
const mdxContainer = useRef(null);

// useEffect(() => {
// setHydrated(true);
// }, []);

// useLayoutEffect(() => {
// if (hydrated && format === 'pdf') {
// const paged = new Previewer();
// let flow = paged.preview(mdxContainer.current.innerHTML, [], document.body).then((flow) => {
// console.log("Rendered", flow.total, "pages.");
// })
// // paged
// // .preview(mdxContainer.current.innerHTML, [], document.body)
// // .then((flow) => {
// // console.log('Rendered', flow.total, 'pages.');
// // });
// }
// }, [hydrated, mdxContainer]);
const previewContainer = useRef(null);
let contentMdx = ``;
useLayoutEffect(() => {
if (source && format === 'pdf') {
const element = document.querySelector('#pdf-element');
const paged = new Previewer();
let flow = paged.preview(mdxContainer.current.innerHTML, [pageStyle], document.body).then((flow) => {
console.log("Rendered", flow.total, "pages.");
})
}
}, [source]);
const paged = new Previewer();
contentMdx = `${mdxContainer.current?.innerHTML}`;
paged
.preview(contentMdx,
[],
previewContainer.current
)
.then((flow) => {
console.log('====flow====')
console.log(flow)
const pagedjs_pages = document.getElementsByClassName('pagedjs_pages');
console.log(pagedjs_pages);

});
return () => {
document.head
.querySelectorAll("[data-pagedjs-inserted-styles]")
.forEach((e) => e.parentNode?.removeChild(e));
};
}

}, [source])

if (format === 'pdf') {
console.log('Rendering PDF View')
return (
<div ref={mdxContainer} style={{backgroundColor: 'lightgrey'}}>
{/* style={{ display: 'none' }}> */}
return (
<>
<Head>
<Script src="https://unpkg.com/pagedjs/dist/paged.polyfill.js"></Script>
</Head>
<div ref={mdxContainer} style={{ display: 'none' }}>
{/* style={{ display: 'none' }}> */}
<ThemeProvider theme={theme}>
<CssBaseline />
{source && <MDXRemote {...source} components={mdComponents} />}
</ThemeProvider>
</div>
<div className="pagedjs_page" ref={previewContainer}></div>
</>
)
} else {
return (
<ThemeProvider theme={theme}>
<CssBaseline />
{source && <MDXRemote {...source} components={mdComponents} />}
</ThemeProvider>
</div>
)
} else {
return (

<ThemeProvider theme={theme}>
<CssBaseline />
{source && <MDXRemote {...source} components={mdComponents} />}
</ThemeProvider>


)

}
Expand Down
86 changes: 86 additions & 0 deletions styles/pdf.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
:root {
--color-white: #fdfdfd;
--shadow-black: rgba(0, 0, 0, 0.2);
--margin: 4px;
font-size: 18px;
}
html {
color: #393939;
font-family: "Heebo";
/* font-size: 22px; */
font-weight: 300;
font-size: 11pt;
line-height: 1.5;
margin: 0 auto;
max-width: 768px;
}

html body h1 {
color: #002b3d;
/* color: #fff; */
font-size: 28pt;
margin: 0cm 0cm 0cm 0cm;
break-before: always;
width: 100%;
}

.pagedjs_page {
background-color: var(--color-white);
margin: 10px auto;
flex: none;
box-shadow: 0 0 0 1px var(--shadow-black);
}

@page {
size: A4;
@top-left {
background: #4ac7f0;
content: "";
display: block;
height: 0.05cm;
opacity: 0.5;
width: 100%;
}

@top-center {
background: #4ac7f0;
content: "";
display: block;
height: 0.05cm;
opacity: 0.5;
width: 100%;
}

@top-right {
content: string(heading);
font-size: 9pt;
height: 1cm;
vertical-align: middle;
width: 100%;
}

@bottom-center {
background: #4ac7f0;
content: "";
display: block;
height: 0.05cm;
opacity: 0.5;
width: 100%;
}

@bottom-right {
background: #4ac7f0;
content: "Page " counter(page) " of " counter(pages);
height: 1cm;
text-align: center;
width: 1cm;
}
}

@media print {
h1 {
page-break-before: always !important;
break-before: always !important;
-webkit-break-before: always !important;
}
}

0 comments on commit 56ead17

Please sign in to comment.