The best way to print data in a portal is to use a layout that does not have a portal. Use a list view layout based on the portal's table with data from the parent table included in the header, footer, grand summary or sub summary layout parts of that layout. The script performs a find or uses Go To Related records to pull up the correct set of records and then prints, previews or saves as PDF depending on the needs of the user.
The Invoices starter solution uses this method to print invoices if you want to see a working example.
And the user need not know that this extra layout even exists. They can just click a print button on the current layout and the script can do the rest, returning to the original layout when finished.
The second best way--and this sometimes cannot be avoided, is to set up a second layout with a very tall portal with many more rows than you expect to need. You then set the portal and all objects in the same layout part located below it, to "slide up" and to "resize enclosing part". This then causes the portal to shrink down to just the number of rows needed to show the data in the portal.
And here's a big part about why this is the "second best" approach:
Key facts about sliding layout objects:
- It's only visible in preview mode and when you print/save as PDF...
- Sliding fields will shrink but not expand.
- All layout objects below and in the same layout part as the slide/resize field need to also be set to slide up and resize.
- Objects in headers and footers will not slide.
- Portals will shrink/slide to fit the number of rows of records, but fields within the portal row will not shrink/slide.
- Fields will slide up only if Top alignment is specified for it and will slide left only if Left alignment is specified.
- Consistent side borders are difficult to achieve with sliding fields.