如何调整DOMPDF导出PDF的页面尺寸以适配表单内容?
Hey there! Let's tackle that frustrating DOMPDF paper size problem you're facing with your large bank credit form. It sounds like both your default paper size and custom size attempts are throwing errors—let's break down what might be going wrong and how to fix it.
First, Let's Diagnose the Two Methods You Tried
1. Using DEFAULT_PDF_PAPER_SIZE
Your code:
$dompdf->set_paper(DEFAULT_PDF_PAPER_SIZE, 'portrait');
The issue here is likely that the DEFAULT_PDF_PAPER_SIZE constant isn't properly defined in your environment. Maybe you forgot to include DOMPDF's config file, or the constant name changed in your DOMPDF version.
Quick fix: Replace the constant with an explicit paper size string instead. For example:
// Use standard sizes like 'A4', 'Letter', etc. $dompdf->set_paper('A4', 'portrait');
This bypasses any constant-related issues and ensures DOMPDF recognizes the paper size immediately.
2. Custom Paper Size with an Array
Your code:
$customPaper = array(0,0,360,360); $dompdf->set_paper($customPaper);
The problem here is the format of your custom size array. DOMPDF expects custom paper sizes to be a 2-element array (width, height) in points (1 inch = 72 points), not a 4-element array (which would apply to margins, not page dimensions).
Correct custom size setup:
// 5x5 inch paper (5*72 = 360 points) $customPaper = array(360, 360); $dompdf->set_paper($customPaper, 'portrait'); // 'portrait' is optional here
If you need to set margins alongside the custom size, use CSS @page rules instead (more on that below).
Additional Fixes for Content Fit
Even if you get the paper size right, your large form might still overflow if your CSS isn't optimized for PDF output. Try these tweaks:
- Restrict container widths: Add this CSS to your form's outer container to ensure it doesn't exceed the page bounds:
.form-container { width: 100%; max-width: 100%; box-sizing: border-box; }
- Use CSS
@pagerules for better control: Sometimes defining page dimensions directly in CSS is more reliable than PHP code. Add this to your stylesheet:
@page { size: 5in 5in; /* Matches your 360x360 point custom size */ margin: 10px; /* Adjust margins as needed */ }
This overrides PHP-set paper settings in many cases and gives you finer control over page layout.
Check Your DOMPDF Version
If none of the above works, double-check your DOMPDF version. Older versions had different syntax for custom paper sizes. For example, in very old versions, you might need to use:
$dompdf->set_paper('custom', array(360, 360));
If you're on a super outdated version, consider upgrading to the latest stable release—this will fix many bugs and add better support for modern CSS and paper size configurations.
If Errors Persist...
If you're still getting specific error messages (like "Invalid paper size" or missing constant warnings), share those details, and we can narrow down the issue even further.
内容的提问来源于stack exchange,提问作者Josue Marin

