disable fit to screen and set exact dimensions on svg for png export

This commit is contained in:
Gavin Nishizawa 2023-02-27 19:06:13 -08:00
parent 229cac01cc
commit 2782432d85
No known key found for this signature in database
GPG key ID: AE3B177777CE55CD
2 changed files with 19 additions and 7 deletions

View file

@ -375,11 +375,13 @@ func render(ctx context.Context, ms *xmain.State, compileDur time.Duration, plug
}
func _render(ctx context.Context, ms *xmain.State, plugin d2plugin.Plugin, sketch bool, pad int64, themeID int64, darkThemeID *int64, outputPath string, bundle, forceAppendix bool, page playwright.Page, ruler *textmeasure.Ruler, diagram *d2target.Diagram) ([]byte, error) {
toPNG := filepath.Ext(outputPath) == ".png"
svg, err := d2svg.Render(diagram, &d2svg.RenderOpts{
Pad: int(pad),
Sketch: sketch,
ThemeID: themeID,
DarkThemeID: darkThemeID,
SetDimensions: toPNG,
})
if err != nil {
return nil, err
@ -396,12 +398,12 @@ func _render(ctx context.Context, ms *xmain.State, plugin d2plugin.Plugin, sketc
svg, bundleErr2 = imgbundler.BundleRemote(ctx, ms, svg)
bundleErr = multierr.Combine(bundleErr, bundleErr2)
}
if forceAppendix && filepath.Ext(outputPath) != ".png" {
if forceAppendix && !toPNG {
svg = appendix.Append(diagram, ruler, svg)
}
out := svg
if filepath.Ext(outputPath) == ".png" {
if toPNG {
svg := appendix.Append(diagram, ruler, svg)
if !bundle {

View file

@ -63,6 +63,8 @@ type RenderOpts struct {
Sketch bool
ThemeID int64
DarkThemeID *int64
// disables the fit to screen behavior and ensures the exported svg has the exact dimensions
SetDimensions bool
}
func dimensions(diagram *d2target.Diagram, pad int) (left, top, width, height int) {
@ -1602,6 +1604,7 @@ func Render(diagram *d2target.Diagram, opts *RenderOpts) ([]byte, error) {
pad := DEFAULT_PADDING
themeID := DEFAULT_THEME
darkThemeID := DEFAULT_DARK_THEME
setDimensions := false
if opts != nil {
pad = opts.Pad
if opts.Sketch {
@ -1613,6 +1616,7 @@ func Render(diagram *d2target.Diagram, opts *RenderOpts) ([]byte, error) {
}
themeID = opts.ThemeID
darkThemeID = opts.DarkThemeID
setDimensions = opts.SetDimensions
}
buf := &bytes.Buffer{}
@ -1757,9 +1761,15 @@ func Render(diagram *d2target.Diagram, opts *RenderOpts) ([]byte, error) {
h += int(math.Ceil(float64(diagram.Root.StrokeWidth)/2.) * 2.)
}
fitToScreenWrapper := fmt.Sprintf(`<svg %s preserveAspectRatio="xMidYMid meet" viewBox="0 0 %d %d">`,
var dimensions string
if setDimensions {
dimensions = fmt.Sprintf(` width="%d" height="%d"`, w, h)
}
fitToScreenWrapper := fmt.Sprintf(`<svg %s preserveAspectRatio="xMidYMid meet" viewBox="0 0 %d %d"%s>`,
`xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"`,
w, h,
dimensions,
)
// TODO minify