unidoc / unipdf

Golang PDF library for creating and processing PDF files (pure go)
https://unidoc.io
Other
2.54k stars 250 forks source link

Improve table rendering speed #318

Closed schooltech closed 4 years ago

schooltech commented 4 years ago

I use unipdf to generate a pdf file, the file has 10 columns, 652 lines, Chinese characters, the generated table is 42 pages long, the entire process consumes 33.76 seconds, the font used is microsoft.ttf, how to optimize to provide performance, improve rendering speed?

gunnsth commented 4 years ago

@schooltech Can you provide a full example that we can run to reproduce this?

schooltech commented 4 years ago

pdf_test.zip

gunnsth commented 4 years ago

Thanks for reporting. That certainly looks like a bug. We will look into it.

gunnsth commented 4 years ago

Profiling reveals: image Seems like the font serialization is not cached (PdfFont.ToPdfObject())

I tried adding caching in font.go:

// ToPdfObject converts the PdfFont object to its PDF representation.
func (font *PdfFont) ToPdfObject() core.PdfObject {
    if font.context == nil {
        common.Log.Debug("ERROR: font context is nil")
        return core.MakeNull()
    }
    if font.cached == nil {
        font.cached = font.context.ToPdfObject()
    }
    return font.cached

which reduces the report generation time to 1.5sec.

The file is also pretty big (9MB), which would be improved with font subsetting (#321, #17 ).

@adrg can you take a look at this? Is this the right place to do the caching or would it be better in the creator? It seems like this info should not be changing, so seems like caching would make sense.

schooltech commented 4 years ago

@gunnsth thanks for your reply, has the code been updated?

adrg commented 4 years ago

@gunnsth I think it might be safer to cache the CMap data returned by the CMap.Bytes method as the CMap content is very unlikely to change.

I made some tests on my computer and the difference in execution time is minor:

font ToPdfObject caching: 1.59636693s
CMap data caching: 1.612317699s
gunnsth commented 4 years ago

@adrg OK. Can you make a PR for this?

adrg commented 4 years ago

Sure.

gunnsth commented 4 years ago

@schooltech This is completed and included in v3.6.2

schooltech commented 4 years ago

@gunnsth render slowly again after upgrade to the new version 3.8.0, you can run the same sample project above