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.
To combine multiple HTML documents into a single PDF that allows content to flow seamlessly, you need to merge the HTML content in a way that preserves the structure, styles, and layout. Below are several approaches to achieve this, along with their benefits and risks:
This involves combining the content of all HTML files into a single HTML document before converting it to a PDF.
BeautifulSoup or lxml.<body> content from each HTML file.<body> tag.from bs4 import BeautifulSoup
def combine_html_files(html_files):
combined_html = "<html><head></head><body>"
for html_file in html_files:
with open(html_file, encoding='utf-8') as f:
soup = BeautifulSoup(f, 'html.parser')
# Add a separator or header for clarity
combined_html += f"<h1>{html_file.stem}</h1>"
combined_html += str(soup.body)
combined_html += "</body></html>"
return combined_html
async def _combine(directory: Path, pattern: str = "*.html"):
html_files = list(directory.glob(pattern))
combined_html = combine_html_files(html_files)
# Write combined HTML to a temporary file
combined_html_path = directory / "combined.html"
with open(combined_html_path, "w", encoding="utf-8") as f:
f.write(combined_html)
# Convert combined HTML to PDF
pdf_path = directory / f"{directory.parent.name}_{directory.name}_combined.pdf"
write_pdf_weasy(str(combined_html_path), str(pdf_path))
# Clean up temporary file
os.remove(combined_html_path)
Convert each HTML file into a structured intermediate format (e.g., Markdown, XML) before merging them into a single HTML document.
markdownify.from markdownify import markdownify
def combine_markdown_files(html_files):
combined_markdown = ""
for html_file in html_files:
with open(html_file, encoding='utf-8') as f:
html_content = f.read()
markdown_content = markdownify(html_content)
combined_markdown += f"# {html_file.stem}\n\n{markdown_content}\n\n---\n"
return combined_markdown
async def _combine(directory: Path, pattern: str = "*.html"):
html_files = list(directory.glob(pattern))
combined_markdown = combine_markdown_files(html_files)
# Convert Markdown back to HTML
combined_html = markdown.markdown(combined_markdown)
combined_html_path = directory / "combined.html"
with open(combined_html_path, "w", encoding="utf-8") as f:
f.write(combined_html)
# Convert combined HTML to PDF
pdf_path = directory / f"{directory.parent.name}_{directory.name}_combined.pdf"
write_pdf_weasy(str(combined_html_path), str(pdf_path))
# Clean up temporary file
os.remove(combined_html_path)
Create a master HTML template with placeholders for dynamic content. Insert the content of each HTML file into the template before rendering.
def create_master_template(html_files):
template = """
<html>
<head>
<style>
/* Add global styles here */
</style>
</head>
<body>
{}
</body>
</html>
"""
combined_content = ""
for html_file in html_files:
with open(html_file, encoding='utf-8') as f:
soup = BeautifulSoup(f, 'html.parser')
combined_content += f"<h1>{html_file.stem}</h1>{str(soup.body)}"
return template.format(combined_content)
async def _combine(directory: Path, pattern: str = "*.html"):
html_files = list(directory.glob(pattern))
master_html = create_master_template(html_files)
# Write master HTML to a temporary file
master_html_path = directory / "master.html"
with open(master_html_path, "w", encoding="utf-8") as f:
f.write(master_html)
# Convert master HTML to PDF
pdf_path = directory / f"{directory.parent.name}_{directory.name}_combined.pdf"
write_pdf_weasy(str(master_html_path), str(pdf_path))
# Clean up temporary file
os.remove(master_html_path)
Use a server-side tool like Puppeteer or Playwright to render multiple HTML files sequentially into a single PDF.
async def write_pdf_combined(html_files, pdf_path):
async with async_playwright() as p:
browser = await p.chromium.launch()
page = await browser.new_page()
# Create a blank HTML document
await page.set_content("<html><body></body></html>")
for html_file in html_files:
with open(html_file, encoding='utf-8') as f:
html_content = f.read()
# Append content to the body
await page.evaluate(f"""
const body = document.querySelector('body');
body.insertAdjacentHTML('beforeend', `{html_content}`);
""")
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()
async def _combine(directory: Path, pattern: str = "*.html"):
html_files = list(directory.glob(pattern))
pdf_path = directory / f"{directory.parent.name}_{directory.name}_combined.pdf"
await write_pdf_combined(html_files, pdf_path)
For most use cases, Approach 1 (Concatenate HTML Content) is the most practical and efficient solution. It balances simplicity, flexibility, and performance while allowing for seamless content flow. However, if you encounter style conflicts or need advanced layout control, consider using Approach 3 (Single HTML Template) or Approach 4 (Server-Side Rendering).