GemBox Support Forum

Set page width based on the content

I want to generate pdf/word with Gembox from HTML, the content is dynamic, how can i set a correct width?
for example, i generate a table,
<table style="width:1000px" >…</table>
then, I have to set page size on .cs code:
var document = DocumentModel.Load(htmlStream, htmlLoadOptions);

            document.Sections[0].PageSetup = new PageSetup
                PageWidth = 1000,
                PageHeight = 1000* 4 / 3

this almost works, but the empty space between the table is too much, also, the table is 1000px, i set pageWidth as 1000, but there are some more spaces, yes, the unit of pageWidth is point, I tried to set table width as 1000pt, the content is overflow, so how can I set exactly width of page based by the content?

I can use any unit for the html, for example cm, em, pt, just need to control the width of the page based on the content.


Hi Chandler,

So if I understood you correctly, you want to export everything as a single page, is that correct?

In that case, I would actually suggest you use GemBox.Spreadsheet because it can specify ExcelWorksheet.PrintOptions.FitWorksheetWidthToPages and ExcelWorksheet.PrintOptions.FitWorksheetHeightToPages properties. Setting those to 1 will result in the sheet’s content being exported as a single page.

You can set PageWidth to 1000px like this:

var pageSetup = document.Sections[0].PageSetup;
pageSetup.PageWidth = LengthUnitConverter.Convert(1000, LengthUnit.Pixel, LengthUnit.Point);
pageSetup.PageMargins.Left = 0;
pageSetup.PageMargins.Right = 0;

Or in HTML like this:

  @page {
    size: 1000px 1500px;
    margin: 0;

There is no such option in Word documents and thus there is no such API in the DocumentModel object.


Thanks, problem solved, I have one more question, i also want to convert html to excel, my current code is:

using (var htmlStream = new MemoryStream(htmlLoadOptions.Encoding.GetBytes(html)))
    // Load input HTML text as stream.
    var document = DocumentModel.Load(htmlStream, htmlLoadOptions);

    //document.Sections[0].PageSetup = new PageSetup
    //    PageWidth = _tableWidth,
    //    PageHeight = _tableWidth * 4 / 3
    // Save output PDF file.
    var stream = new MemoryStream();
    document.Save(stream, SaveOptions.PdfDefault);

    return stream;

seems saveOptions don’t have option for excel, is excel can only generated by html with the code:

var htmlOptions = new HtmlLoadOptions();
var htmlStream = new MemoryStream(htmlOptions.Encoding.GetBytes(_stringBuilder.ToString()));

var workbook = ExcelFile.Load(htmlStream, htmlOptions);

is there a way to generate excel but no need to save as a local file but get a stream?

Yes, you cannot save DocumentModel to Excel, you need to use ExcelFile from GemBox.Spreadsheet.

Also, yes, you can save to stream like this:

var xlsxStream = new MemoryStream();
workbook.Save(xlsxStream, SaveOptions.XlsxDefault);
1 Like