aspose-words / Aspose.Words-for-.NET

Aspose.Words for .NET examples, plugins and showcases
https://products.aspose.com/words/net
MIT License
503 stars 187 forks source link

How can I create a document with dynamic height #242

Closed philwu closed 5 years ago

philwu commented 5 years ago

I am trying to generate some documents like receipts and their height will depends on the length of the contents. Is there any way that I can achieve this?

awaishafeez commented 5 years ago

@philwu,

Please note that the maximum allowed width/height that you can specify by using MS Word 2019 is 22 inches (55.88 cm). Similarly, the minimum allowed width/height that you can specify by using MS Word 2019 is 0.1 inches (0.254 cm).

By default, Aspose.Words saves to a Letter size page with the following Width and Height respectively: 8.5 inches by 11 inches.

So, you can build logic on the following code to achieve what you are looking for:

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// grow page height by adding some content
builder.Font.Size = 6;
for (int i = 0; i < 20; i++)
{
    builder.Writeln("Line # " + i);
}

doc.FirstSection.Body.LastParagraph.Remove();
// remove header/footer areas
PageSetup ps = doc.FirstSection.PageSetup;
ps.TopMargin = ps.BottomMargin = 0;

int pageCount = doc.PageCount;
// we cannot process height more than 22 inches (11 + 11)
if (pageCount < 3)
{
    if (pageCount == 2)
    {
        // increase height to maximum
        ps.PageHeight = 22 * 72; 
        doc.UpdatePageLayout();
    }

    LayoutCollector collector = new LayoutCollector(doc);
    LayoutEnumerator enumerator = new LayoutEnumerator(doc);

    enumerator.Current = collector.GetEntity(doc.FirstSection.Body.LastParagraph);
    ps.PageHeight = enumerator.Rectangle.Bottom + 9;
}

doc.Save("E:\\Temp\\19.9.docx");

Hope, this helps.

romeokromeok commented 5 years ago

@philwu did the above reply help you?

AlexNosk commented 5 years ago

No feedback from the customer. Close the issue.