Why was my page size or margin ignored?
There are three ways this happens and they have nothing to do with each other. Work down the list.
You used c.Draw
c.Draw(document) renders at the creator’s page size and applies the creator’s margins. Page
settings on the unihtml.Document are ignored, so SetPageSize(sizes.A5) followed by
c.Draw gives you a Letter page.
Take the pages instead, or write the file directly:
pages, err := doc.GetPdfPages(ctx)Or, when the converted HTML is the whole file:
err := doc.WriteToFile("out.pdf")There is a second-order effect on this path. SetPageSize also switches the document to
absolute positioning, which pins the rendered block to (0, 0) rather than flowing it, so an
A5 document drawn onto a Letter page ends up in the top-left corner with the rest of the sheet
blank. If you are drawing, do not set geometry at all.
You set one margin on its own
A new document is in relative positioning, and while it stays relative all four margins are
overwritten with 1mm just before the request goes out. SetMarginLeft and its three siblings
do not change that, so on their own they are discarded silently. Measured on Letter:
| Calls | Left margin in the output |
|---|---|
SetMarginLeft(sizes.Millimeter(50)) | 2pt, the forced 1mm |
SetMargins(0, 0, 0, 0) then SetMarginLeft(sizes.Millimeter(50)) | 141pt, correct |
SetPageSize(sizes.A5) then SetMarginLeft(sizes.Millimeter(50)) | 141pt, correct |
SetMargins, SetPageSize, SetPageWidth, SetPageHeight and SetPos each switch
positioning to absolute. Call one of them first and the individual setters work.
SetLandscapeOrientation does not, so it is no help.
The simplest fix is to use SetMargins for all four at once. It takes points as bare
float64 values, in the order left, right, top, bottom:
doc.SetMargins(40, 40, 40, 40)That order is not the CSS one. CSS shorthand goes clockwise from the top.
Your value was fractional
Lengths are serialized with no decimal places, so a fraction is rounded before the server ever sees it. Half an inch becomes zero:
| You write | Server receives |
|---|---|
sizes.Inch(0.5) | 0in, no margin |
sizes.Inch(1) | 1in |
sizes.Millimeter(12.7) | 13mm |
sizes.Point(10.4) | 10pt |
Use millimeters or points, which are fine enough for page margins. Half an inch is
sizes.Millimeter(13).
Do not convert with sizes.Inch(x).Points() to get around it. That conversion is wrong in the
current release and returns 0.0pt for one inch.
Bonus: you expected A4
With no page calls at all the output is Letter, 612 by 792 points, regardless of the machine’s locale. Set it explicitly:
if err := doc.SetPageSize(sizes.A4); err != nil {
return err
}And if you set both size and dimensions
SetPageSize wins over SetPageWidth and SetPageHeight in either call order, because the
server applies the named size last and it overwrites the explicit values. Pick one.
Margins and page size and orientation have the detail.