nextra icon indicating copy to clipboard operation
nextra copied to clipboard

Need help with Export to PDF in Nextra

Open luke-klein opened this issue 2 years ago • 5 comments

Hey, I've been trying to implement the GitBook export as a PDF component, and I've tested a lot of libraries. Unfortunately, I haven't been able to implement it properly. I did find one library that works, but it doesn't create a proper PDF. Does anyone know of a better option, or is it possible to implement this feature by default in Nextra? Any help would be greatly appreciated!

GitBook image


My solution was

Here's the solution I've tried so far, including the PDFButton component and theme.config.tsx code:

PDFButton

import React, { useRef } from 'react';
import html2canvas from 'html2canvas';
import jsPDF from 'jspdf';

const PDFButton = () => {
    const contentRef = useRef(null);

    const handleExportPDF = () => {
        const input = document.getElementById('pdf-content');
        html2canvas(input).then(canvas => {
            console.log(canvas); // log the canvas object
            const imgData = canvas.toDataURL('image/png');
            const pdf = new jsPDF({
                orientation: 'landscape',
                unit: 'px',
                format: [720, 720],
                compress: true,
            });
            pdf.addImage(imgData, 'PNG', 0, 0, 35, 420);
            pdf.save('export.pdf');
        });
    };

    return (
        <button
            onClick={handleExportPDF}
            className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded"
        >
            Export as PDF
        </button>
    );
};

export default PDFButton;

theme.config.tsx

    main: ({ children }) => {
        return (
            <>
                <div id="pdf-content">{children}</div>
                <PDFButton />
                <BackToTop />
                <GiscusComments />
            </>
        );
    }

} as DocsThemeConfig

image

luke-klein avatar Feb 26 '23 06:02 luke-klein