Skip to content

Replace phantomjs with playwright chromium for PDF generation to support ARM64 #1926

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

Open
wants to merge 6 commits into
base: develop
Choose a base branch
from
Open
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
46 changes: 35 additions & 11 deletions lib/note/noteActions.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@

const fs = require('fs')
const path = require('path')
const markdownpdf = require('markdown-pdf')
const shortId = require('shortid')
const querystring = require('querystring')
const moment = require('moment')
const { Pandoc } = require('@hackmd/pandoc.js')
const { convertMarkdownToPDF } = require('../utils/markdown-to-pdf')

const config = require('../config')
const logger = require('../logger')
Expand Down Expand Up @@ -64,7 +64,7 @@ function actionInfo (req, res, note) {
res.send(data)
}

function actionPDF (req, res, note) {
async function actionPDF (req, res, note) {
const url = config.serverURL || 'http://' + req.get('host')
const body = note.content
const extracted = Note.extractMeta(body)
Expand All @@ -78,14 +78,17 @@ function actionPDF (req, res, note) {
}
const pdfPath = config.tmpPath + '/' + Date.now() + '.pdf'
content = content.replace(/\]\(\//g, '](' + url + '/')
const markdownpdfOptions = {
highlightCssPath: highlightCssPath
}
markdownpdf(markdownpdfOptions).from.string(content).to(pdfPath, function () {

try {
await convertMarkdownToPDF(content, pdfPath, {
highlightCssPath: highlightCssPath
})

if (!fs.existsSync(pdfPath)) {
logger.error('PDF seems to not be generated as expected. File doesn\'t exist: ' + pdfPath)
return errorInternalError(req, res)
}

const stream = fs.createReadStream(pdfPath)
let filename = title
// Be careful of special characters
Expand All @@ -95,12 +98,33 @@ function actionPDF (req, res, note) {
res.setHeader('Cache-Control', 'private')
res.setHeader('Content-Type', 'application/pdf; charset=UTF-8')
res.setHeader('X-Robots-Tag', 'noindex, nofollow') // prevent crawling
stream.on('end', () => {
stream.close()
fs.unlinkSync(pdfPath)
})

// Cleanup file after streaming
const cleanup = () => {
try {
if (fs.existsSync(pdfPath)) {
fs.unlinkSync(pdfPath)
}
} catch (err) {
logger.error('Failed to cleanup PDF file:', err)
}
}

stream.on('end', cleanup)
stream.on('error', cleanup)
stream.pipe(res)
})
} catch (error) {
logger.error('PDF generation failed:', error)
// Cleanup any partially created file
try {
if (fs.existsSync(pdfPath)) {
fs.unlinkSync(pdfPath)
}
} catch (cleanupError) {
logger.error('Failed to cleanup partial PDF file:', cleanupError)
}
return errorInternalError(req, res)
}
}

const outputFormats = {
Expand Down
179 changes: 179 additions & 0 deletions lib/utils/markdown-to-pdf.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,179 @@
'use strict'

const { chromium } = require('playwright-chromium')
const markdownit = require('markdown-it')
const path = require('path')
const fs = require('fs')

// Configure markdown-it similar to frontend
function createMarkdownRenderer () {
const md = markdownit('default', {
html: true,
breaks: true,
linkify: true,
typographer: true,
highlight: function (str, lang) {
try {
const hljs = require('highlight.js')
if (lang && hljs.getLanguage(lang)) {
return '<pre class="hljs"><code>' +
hljs.highlight(lang, str, true).value +
'</code></pre>'
}
} catch (error) {
// Fall back to no highlighting
}
return '<pre class="hljs"><code>' + md.utils.escapeHtml(str) + '</code></pre>'
}
})

// Add plugins commonly used in CodiMD
try {
md.use(require('markdown-it-abbr'))
md.use(require('markdown-it-footnote'))
md.use(require('markdown-it-deflist'))
md.use(require('markdown-it-mark'))
md.use(require('markdown-it-ins'))
md.use(require('markdown-it-sub'))
md.use(require('markdown-it-sup'))
} catch (error) {
// Some plugins may not be available, continue with basic rendering
console.warn('Some markdown-it plugins not available:', error.message)
}

return md
}

async function convertMarkdownToPDF (markdown, outputPath, options = {}) {
const md = createMarkdownRenderer()

// Convert markdown to HTML
const htmlContent = md.render(markdown)

// Read highlight.js CSS
const highlightCssPath = options.highlightCssPath || path.join(__dirname, '../../node_modules/highlight.js/styles/github-gist.css')
let highlightCss = ''

if (fs.existsSync(highlightCssPath)) {
highlightCss = fs.readFileSync(highlightCssPath, 'utf8')
}

// Create full HTML document
const fullHtml = `
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>PDF Export</title>
<style>
${highlightCss}

body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
line-height: 1.6;
color: #333;
max-width: 800px;
margin: 0 auto;
padding: 20px;
}

pre {
background-color: #f6f8fa;
border-radius: 6px;
padding: 16px;
overflow: auto;
}

code {
background-color: #f6f8fa;
border-radius: 3px;
padding: 2px 4px;
font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, monospace;
}

pre code {
background-color: transparent;
padding: 0;
}

h1, h2, h3, h4, h5, h6 {
margin-top: 24px;
margin-bottom: 16px;
font-weight: 600;
line-height: 1.25;
}

blockquote {
padding: 0 1em;
color: #6a737d;
border-left: 0.25em solid #dfe2e5;
margin: 0;
}

table {
border-collapse: collapse;
width: 100%;
}

th, td {
border: 1px solid #dfe2e5;
padding: 6px 13px;
}

th {
background-color: #f6f8fa;
font-weight: 600;
}
</style>
</head>
<body>
${htmlContent}
</body>
</html>`

// Launch Playwright Chromium and generate PDF
let browser = null
try {
browser = await chromium.launch({
headless: true,
args: ['--no-sandbox', '--disable-setuid-sandbox', '--disable-dev-shm-usage']
})

const page = await browser.newPage()

// Set a timeout for page operations
page.setDefaultTimeout(30000)

await page.setContent(fullHtml, {
waitUntil: 'networkidle'
})

await page.pdf({
path: outputPath,
format: 'A4',
margin: {
top: '20px',
right: '20px',
bottom: '20px',
left: '20px'
},
printBackground: true
})

return true
} catch (error) {
throw new Error(`PDF generation failed: ${error.message}`)
} finally {
if (browser) {
try {
await browser.close()
} catch (closeError) {
console.warn('Failed to close browser:', closeError.message)
}
}
}
}

module.exports = {
convertMarkdownToPDF
}
Loading