Untitled conversation
- User
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
import asyncio
from playwright.async_api import async_playwright
from pathlib import Path
from PyPDF2 import PdfMerger
import os
import logging
from weasyprint import HTML, CSS
logger = logging.getLogger(__name__)
# def convert_html_to_pdf(html_path, pdf_path):
# """Convert HTML file to PDF"""
# options = {
# 'page-size': 'A4',
# 'margin-top': '0.75in',
# 'margin-right': '0.75in',
# 'margin-bottom': '0.75in',
# 'margin-left': '0.75in',
# 'enable-local-file-access': None,
# 'enable-smart-shrinking': None
# }
# with open(html_path, 'r', encoding='utf-8') as file:
# html_content = file.read()
# pdfkit.from_string(html_content, pdf_path, options=options, configuration=pdfkit.configuration(wkhtmltopdf="/usr/bin/wkhtmltopdf"))
def write_pdf_weasy(html_path, pdf_path):
# Read HTML content
with open(html_path, encoding='utf-8') as f:
html_content = f.read()
# Define CSS for two-column layout and pagination
css = CSS(string="""
@page {
size: A4 landscape;
margin: 20px;
}
body {
font-size: 7pt;
font-family: sans-serif;
column-count: 2;
column-gap: 20px;
margin: 0;
padding: 20px;
}
p, h1, h2, h3, blockquote {
break-inside: avoid;
page-break-inside: avoid;
}
h1 {
font-size: 18pt;
}
/* Scale only images inside figures to prevent layout overflow */
figure img {
max-width: 100%;
max-height: 200px;
height: auto;
display: block;
}
/* Prevent figure from breaking awkwardly */
figure {
break-inside: avoid;
}
""")
# Generate PDF
HTML(string=html_content).write_pdf(pdf_path, stylesheets=[css])
async def write_pdf_chromium(html_path, pdf_path):
with open(html_path, encoding='utf-8') as file:
html_content = file.read()
async with async_playwright() as p:
browser = await p.chromium.launch()
page = await browser.new_page()
await page.set_content(html_content)
# Add CSS for two columns and fix height issues
await page.add_style_tag(content="""
html, body {
height: auto !important;
min-height: 100%;
margin: 0;
padding: 20px;
}
body {
column-count: 2;
column-gap: 40px;
column-rule: 1px solid #ddd;
}
p, h1, h2, h3, blockquote {
break-inside: avoid;
page-break-inside: avoid;
}
""")
await page.emulate_media(media="print")
await page.wait_for_timeout(1000)
await page.pdf(
path=pdf_path,
format="A4",
landscape=True,
print_background=True,
margin={"top": "20px", "right": "20px", "bottom": "20px", "left": "20px"}
)
await browser.close()
def merge_pdfs(pdf_files, output_path):
"""Merge multiple PDF files into one"""
merger = PdfMerger()
for pdf in pdf_files:
merger.append(str(pdf))
merger.write(output_path)
logger.debug("Wrote combined PDF", extra={"output_path": output_path})
merger.close()
return output_path
async def _combine(directory: Path, pattern: str = "*.html"):
html_files = list(directory.glob(pattern))
pdf_files = [html.with_name(html.stem + ".pdf") for html in html_files]
for html, pdf in zip(html_files, pdf_files):
write_pdf_weasy(str(html), pdf)
# Remember that the parent's name is the feed id
# and the child is the datetime of its latest entry
# Remember that we assume the directory name is the feed id
outfile_name = f"{directory.parent.name}_{directory.name}_combined.pdf"
# Join the outfile_name with the directory
outfile_path = directory / outfile_name
merge_pdfs(pdf_files, outfile_path)
for pdf in pdf_files:
try:
os.remove(pdf)
logger.debug("Deleted pdf", extra={"filepath": pdf})
except Exception:
logger.error("Failed to delete pdf", extra={"filepath": pdf}, exc_info=True)
Currently this takes multiple arbitrary HTML documents, converts each to a PDF then combines the resulting PDFs. I would like to combine the HTML documents so that they can flow.
What are some approaches to this? Consider benefits and risks of each.
Looking at your code, I see you're currently converting individual HTML files to PDFs with a two-column layout and then merging those PDFs. To make content flow between documents, here are some approaches:
Concatenate HTML before conversion
Use a template system with imports
Server-side rendering approach
Use a document processing library
The main tradeoff is between simplicity and control over the document flow. Concatenating HTML is simplest but might have formatting issues at boundaries. Template systems give more control but require more setup.
Would you like me to explain or provide code examples for any of these approaches?