1
0
Fork 0

pdf export working

This commit is contained in:
Enoch Riese 2022-11-14 14:02:11 -06:00
parent 922cfd02b9
commit d8cb8a7783
9 changed files with 313 additions and 273 deletions

View file

@ -53,7 +53,7 @@ const colors = {
* scale: the scale of the markings * scale: the scale of the markings
* stripped: should nested declarations be stripped out? Necessary for svgToPdfkit * stripped: should nested declarations be stripped out? Necessary for svgToPdfkit
* */ * */
export const buildStylesheet = (scale, stripped) => ` export const buildStylesheet = (scale = 1, stripped) => `
${!stripped ? '/* Reset */' : ''} ${!stripped ? '/* Reset */' : ''}
${!stripped ? 'svg.freesewing ' : ''}path, ${!stripped ? 'svg.freesewing ' : ''}path,
${!stripped ? 'svg.freesewing ' : ''}circle, ${!stripped ? 'svg.freesewing ' : ''}circle,

View file

@ -1,20 +1,16 @@
const Circle = (props) => props.point.attributes.getAsArray('data-circle').map((r,i) => { const Circle = (props) =>
props.point.attributes.getAsArray('data-circle').map((r, i) => {
const circleProps = props.point.attributes.asPropsIfPrefixIs('data-circle-') const circleProps = props.point.attributes.asPropsIfPrefixIs('data-circle-')
const extraProps = {} const extraProps = {}
for (const prop in circleProps) { for (const prop in circleProps) {
const val = props.point.attributes.getAsArray(`data-circle-${(prop === 'className' ? 'class' : prop)}`) const val = props.point.attributes.getAsArray(
`data-circle-${prop === 'className' ? 'class' : prop}`
)
if (val.length >= i) extraProps[prop] = val[i] if (val.length >= i) extraProps[prop] = val[i]
else extraProps[prop] = val.join(' ') else extraProps[prop] = val.join(' ')
} }
return ( return <circle key={r} cx={props.point.x} cy={props.point.y} r={r} {...extraProps} />
<circle })
cx={props.point.x}
cy={props.point.y}
r={r}
{...extraProps}
/>
)
})
export default Circle export default Circle

View file

@ -104,7 +104,7 @@ export const handleExport = async (format, gist, design, t, app, onComplete, onE
// add the strings that are used on the cover page // add the strings that are used on the cover page
workerArgs.strings = { workerArgs.strings = {
design: capitalize(gist.design), design: capitalize(pattern.designConfig.data.name.replace('@freesewing/', '')),
tagline: t('common:sloganCome') + '. ' + t('common:sloganStay'), tagline: t('common:sloganCome') + '. ' + t('common:sloganStay'),
url: window.location.href, url: window.location.href,
} }
@ -112,13 +112,10 @@ export const handleExport = async (format, gist, design, t, app, onComplete, onE
// draft and render the pattern // draft and render the pattern
pattern.draft() pattern.draft()
svg = pattern.render() workerArgs.svg = pattern.render()
// add the svg and pages data to the worker args // add the svg and pages data to the worker args
workerArgs.svg = svg workerArgs.pages = pattern.setStores[pattern.activeSet].get('pages')
if (pattern.parts.pages) {
workerArgs.pages = pattern.parts.pages.pages
}
} catch (err) { } catch (err) {
console.log(err) console.log(err)
app.stopLoading() app.stopLoading()

View file

@ -65,8 +65,8 @@ export default class PdfMaker {
this.rows = pages.rows this.rows = pages.rows
// calculate the width of the svg in points // calculate the width of the svg in points
this.svgWidth = this.columns * pages.width * mmToPoints this.svgWidth = this.columns * this.pageWidth
this.svgHeight = this.rows * pages.height * mmToPoints this.svgHeight = this.rows * this.pageHeight
} }
/** create the pdf document */ /** create the pdf document */
@ -179,7 +179,7 @@ export default class PdfMaker {
preserveAspectRatio: 'xMinYMin slice', preserveAspectRatio: 'xMinYMin slice',
} }
// everything is offset by half a margin so that it's centered on the page // everything is offset by a margin so that it's centered on the page
const startMargin = this.margin const startMargin = this.margin
for (var h = 0; h < this.rows; h++) { for (var h = 0; h < this.rows; h++) {
for (var w = 0; w < this.columns; w++) { for (var w = 0; w < this.columns; w++) {

View file

@ -4,6 +4,7 @@ import Defs from '../../draft/defs'
import Stack from './part' import Stack from './part'
import SvgWrapper from '../../draft/svg-wrapper' import SvgWrapper from '../../draft/svg-wrapper'
import { getProps } from '../../draft/utils' import { getProps } from '../../draft/utils'
import { PartInner } from '../../draft/part'
const Draft = (props) => { const Draft = (props) => {
const { const {
@ -69,8 +70,16 @@ const Draft = (props) => {
? `${layout.topLeft.x} ${layout.topLeft.y} ${layout.width} ${layout.height}` ? `${layout.topLeft.x} ${layout.topLeft.y} ${layout.width} ${layout.height}`
: false : false
const stacks = [] const stacks = [
<PartInner
{...{ part: patternProps.parts[0][props.layoutPart], partName: props.layoutPart, gist }}
key={props.layoutPart}
/>,
]
for (var stackName in patternProps.stacks) { for (var stackName in patternProps.stacks) {
if (stackName === props.layoutPart) {
continue
}
let stack = patternProps.stacks[stackName] let stack = patternProps.stacks[stackName]
const stackPart = ( const stackPart = (
@ -88,7 +97,7 @@ const Draft = (props) => {
/> />
) )
stacks[stack === props.layoutPart ? 'unshift' : 'push'](stackPart) stacks.push(stackPart)
} }
return ( return (

View file

@ -32,7 +32,6 @@ const PrintLayout = (props) => {
// draft the pattern // draft the pattern
draft.draft() draft.draft()
patternProps = draft.getRenderProps() patternProps = draft.getRenderProps()
console.log(patternProps)
} catch (err) { } catch (err) {
console.log(err, props.gist) console.log(err, props.gist)
} }

View file

@ -50,32 +50,32 @@ export const pagesPlugin = ({ size = 'a4', ...settings }) => {
return basePlugin({ ...settings, sheetWidth, sheetHeight }) return basePlugin({ ...settings, sheetWidth, sheetHeight })
} }
const doScanForBlanks = (parts, layout, x, y, w, h) => { const doScanForBlanks = (stacks, layout, x, y, w, h) => {
let hasContent = false let hasContent = false
for (var p in parts) { for (var s in stacks) {
let part = parts[p] let stack = stacks[s]
// skip the pages part and any that aren't rendered
if (part === this || part.render === false || part.isEmpty()) continue
// get the position of the part // get the position of the part
let partLayout = layout.parts[p] let stackLayout = layout.stacks[s]
let partMinX = partLayout.tl?.x || partLayout.move.x + part.topLeft.x if (!stackLayout) continue
let partMinY = partLayout.tl?.y || partLayout.move.y + part.topLeft.y
let partMaxX = partLayout.br?.x || partMinX + part.width
let partMaxY = partLayout.br?.y || partMinY + part.height
// check if the part overlaps the page extents let stackMinX = stackLayout.tl?.x || stackLayout.move.x + stack.topLeft.x
let stackMinY = stackLayout.tl?.y || stackLayout.move.y + stack.topLeft.y
let stackMaxX = stackLayout.br?.x || stackMinX + stack.width
let stackMaxY = stackLayout.br?.y || stackMinY + stack.height
// check if the stack overlaps the page extents
if ( if (
// if the left of the part is further left than the right end of the page // if the left of the stack is further left than the right end of the page
partMinX < x + w && stackMinX < x + w &&
// and the top of the part is above the bottom of the page // and the top of the stack is above the bottom of the page
partMinY < y + h && stackMinY < y + h &&
// and the right of the part is further right than the left of the page // and the right of the stack is further right than the left of the page
partMaxX > x && stackMaxX > x &&
// and the bottom of the part is below the top to the page // and the bottom of the stack is below the top to the page
partMaxY > y stackMaxY > y
) { ) {
// the part has content inside the page // the stack has content inside the page
hasContent = true hasContent = true
// so we stop looking // so we stop looking
break break
@ -107,7 +107,44 @@ const basePlugin = ({
name, name,
version, version,
hooks: { hooks: {
preDraft: function (pattern) { preLayout: function (pattern) {
// Add part
pattern.addPart({
name: partName,
draft: (shorthand) => {
const layoutData = shorthand.store.get('layoutData')
if (layoutData) {
shorthand.macro('addPages', layoutData, shorthand)
shorthand.part.unhide()
} else {
shorthand.part.hide()
}
return shorthand.part
},
})
pattern.getConfig()
pattern.createPartForSet(partName, pattern.activeSet)
},
postLayout: function (pattern) {
let { height, width, stacks } = pattern
if (!responsiveColumns) width = sheetWidth
const layout =
typeof pattern.settings[0].layout === 'object'
? pattern.settings[0].layout
: pattern.autoLayout
if (layout?.topLeft) {
height += layout.topLeft.y
responsiveColumns && (width += layout.topLeft.x)
}
pattern.setStores[pattern.activeSet].set('layoutData', {
size: [sheetHeight, sheetWidth],
height,
width,
layout,
stacks,
})
// But add the part to the autoLayout property // But add the part to the autoLayout property
// pattern.autoLayout.parts[partName] = { // pattern.autoLayout.parts[partName] = {
// move: { x: 0, y: 0 } // move: { x: 0, y: 0 }
@ -116,43 +153,16 @@ const basePlugin = ({
// TODO migrate this to v3 parts adding // TODO migrate this to v3 parts adding
// Add pages // Add pages
// const { macro } = pattern.config.parts[partName].shorthand() // const { macro } = pattern.config.parts[partName].shorthand()
let { height, width } = pattern pattern.draftPartForSet(partName, pattern.activeSet)
if (!responsiveColumns) width = sheetWidth
if (pattern.settings.layout?.topLeft) {
height += pattern.settings.layout.topLeft.y
responsiveColumns && (width += pattern.settings.layout.topLeft.x)
}
// Add part
pattern.addPart({
name: partName,
layout: false,
draft: (shorthand) => {
pluginMacros.addPages(
{ size: [sheetHeight, sheetWidth], height, width, layout },
shorthand
)
return shorthand.part
},
})
pattern.getConfig()
console.log(pattern.config, pattern.designConfig)
const layout =
typeof pattern.settings.layout === 'object' ? pattern.settings.layout : pattern.autoLayout
// macro('addPages', { size: [sheetHeight,sheetWidth, ], height, width, layout })
if (boundary) pattern.parts[partName].boundary()
if (setPatternSize) { if (setPatternSize) {
pattern.width = sheetWidth * pattern.parts[partName].pages.cols const generatedPageData = pattern.setStores[pattern.activeSet].get('pages')
pattern.height = sheetHeight * pattern.parts[partName].pages.rows pattern.width = sheetWidth * generatedPageData.cols
pattern.height = sheetHeight * generatedPageData.rows
} }
}, },
}, },
}) macros: {
const pluginMacros = {
/** draft the pages */ /** draft the pages */
addPages: function (so, shorthand) { addPages: function (so, shorthand) {
const [h, w] = so.size const [h, w] = so.size
@ -161,6 +171,8 @@ const pluginMacros = {
const { points, Point, paths, Path, macro } = shorthand const { points, Point, paths, Path, macro } = shorthand
let count = 0 let count = 0
let withContent = {} let withContent = {}
shorthand.part.topLeft = so.layout.topLeft || { x: 0, y: 0 }
// get the layout from the pattern // get the layout from the pattern
const { layout } = so const { layout } = so
for (let row = 0; row < rows; row++) { for (let row = 0; row < rows; row++) {
@ -170,7 +182,7 @@ const pluginMacros = {
let x = col * w let x = col * w
let hasContent = true let hasContent = true
if (scanForBlanks && layout) { if (scanForBlanks && layout) {
hasContent = doScanForBlanks(this.context.parts, layout, x, y, w, h) hasContent = doScanForBlanks(so.stacks, layout, x, y, w, h)
} }
withContent[row][col] = hasContent withContent[row][col] = hasContent
if (!renderBlanks && !hasContent) continue if (!renderBlanks && !hasContent) continue
@ -181,12 +193,13 @@ const pluginMacros = {
points[`${pageName}-br`] = new Point(x + w, y + h) points[`${pageName}-br`] = new Point(x + w, y + h)
points[`${pageName}-bl`] = new Point(x, y + h) points[`${pageName}-bl`] = new Point(x, y + h)
points[`${pageName}-circle`] = new Point(x + w / 2, y + h / 2) points[`${pageName}-circle`] = new Point(x + w / 2, y + h / 2)
.attr('data-circle', 56) .setCircle(56, 'stroke-4xl muted fabric')
.attr('data-circle-class', 'stroke-4xl muted fabric')
.attr('data-circle-id', `${pageName}-circle`) .attr('data-circle-id', `${pageName}-circle`)
points[`${pageName}-text`] = new Point(x + w / 2, y + h / 2) points[`${pageName}-text`] = new Point(x + w / 2, y + h / 2)
.attr('data-text', `${indexStr(col + 1)}${row + 1}`) .setText(
.attr('data-text-class', 'text-4xl center baseline-center bold muted fill-fabric') `${indexStr(col + 1)}${row + 1}`,
'text-4xl center baseline-center bold muted fill-fabric'
)
.attr('data-text-id', `${pageName}-text`) .attr('data-text-id', `${pageName}-text`)
paths[pageName] = new Path() paths[pageName] = new Path()
@ -197,6 +210,13 @@ const pluginMacros = {
.line(points[`${pageName}-tr`]) .line(points[`${pageName}-tr`])
.close() .close()
if (col === cols - 1 && row === rows - 1) {
const br = points[`${pageName}-br`]
shorthand.part.width = br.x
shorthand.part.height = br.y
shorthand.part.bottomRight = { x: br.x, y: br.y }
}
if (!printStyle) { if (!printStyle) {
paths[pageName] paths[pageName]
.attr('class', 'fill-fabric') .attr('class', 'fill-fabric')
@ -207,14 +227,14 @@ const pluginMacros = {
} else { } else {
paths[pageName].attr('class', 'interfacing stroke-xs') paths[pageName].attr('class', 'interfacing stroke-xs')
// add markers and rulers // add markers and rulers
pluginMacros.addPageMarkers({ row, col, pageName, withContent }, shorthand) shorthand.macro('addPageMarkers', { row, col, pageName, withContent }, shorthand)
pluginMacros.addRuler({ xAxis: true, pageName }, shorthand) shorthand.macro('addRuler', { xAxis: true, pageName }, shorthand)
pluginMacros.addRuler({ xAxis: false, pageName }, shorthand) shorthand.macro('addRuler', { xAxis: false, pageName }, shorthand)
} }
} }
} }
// Store page count in part // Store page count in part
shorthand.part.pages = { cols, rows, count, withContent, width: w, height: h } shorthand.store.set(partName, { cols, rows, count, withContent, width: w, height: h })
}, },
/** add a ruler to the top left corner of the page */ /** add a ruler to the top left corner of the page */
addRuler({ xAxis, pageName }, shorthand) { addRuler({ xAxis, pageName }, shorthand) {
@ -229,7 +249,10 @@ const pluginMacros = {
const rulerName = `${pageName}-${axisName}` const rulerName = `${pageName}-${axisName}`
// start by making an endpoint for the ruler based on the axis // start by making an endpoint for the ruler based on the axis
const endPoint = [endPointDist[xAxis ? 0 : 1], endPointDist[xAxis ? 1 : 0]] const endPoint = [endPointDist[xAxis ? 0 : 1], endPointDist[xAxis ? 1 : 0]]
points[`${rulerName}-ruler-end`] = points[`${pageName}-tl`].translate(endPoint[0], endPoint[1]) points[`${rulerName}-ruler-end`] = points[`${pageName}-tl`].translate(
endPoint[0],
endPoint[1]
)
// also make a tick for the end of the ruler // also make a tick for the end of the ruler
points[`${rulerName}-ruler-tick`] = points[`${rulerName}-ruler-end`] points[`${rulerName}-ruler-tick`] = points[`${rulerName}-ruler-end`]
.translate(xAxis ? 0 : 3, xAxis ? 3 : 0) .translate(xAxis ? 0 : 3, xAxis ? 3 : 0)
@ -334,4 +357,5 @@ const pluginMacros = {
// give it an explicit ID in case we need to hide it later // give it an explicit ID in case we need to hide it later
.attr('id', markerName) .attr('id', markerName)
}, },
} },
})

View file

@ -6,24 +6,32 @@ import ClearIcon from 'shared/components/icons/clear'
import ExportIcon from 'shared/components/icons/export' import ExportIcon from 'shared/components/icons/export'
import { useTranslation } from 'next-i18next' import { useTranslation } from 'next-i18next'
const PrintLayoutSettings = props => { const PrintLayoutSettings = (props) => {
if (!props.draft?.parts?.pages?.pages) return null let pages = props.draft?.setStores[0].get('pages')
const { cols, rows, count } = props.draft.parts.pages.pages if (!pages) return null
const { cols, rows, count } = pages
const { t } = useTranslation(['workbench']) const { t } = useTranslation(['workbench'])
const setMargin = (evt) => { const setMargin = (evt) => {
props.updateGist(['_state', 'layout', 'forPrinting', 'page', 'margin'], parseInt(evt.target.value)) props.updateGist(
['_state', 'layout', 'forPrinting', 'page', 'margin'],
parseInt(evt.target.value)
)
} }
const setCoverPage = () => { const setCoverPage = () => {
props.updateGist(['_state', 'layout', 'forPrinting', 'page', 'coverPage'], !props.layoutSettings.coverPage) props.updateGist(
['_state', 'layout', 'forPrinting', 'page', 'coverPage'],
!props.layoutSettings.coverPage
)
} }
return ( return (
<div > <div>
<div className="flex flex-row justify-between <div
mb-2"> className="flex flex-row justify-between
mb-2"
>
<div className="flex gap-4"> <div className="flex gap-4">
<PageSizePicker {...props} /> <PageSizePicker {...props} />
<OrientationPicker {...props} /> <OrientationPicker {...props} />
@ -34,15 +42,17 @@ const PrintLayoutSettings = props => {
onClick={props.exportIt} onClick={props.exportIt}
className="btn btn-primary btn-outline" className="btn btn-primary btn-outline"
disabled={count === 0} disabled={count === 0}
aria-disabled={count === 0}> aria-disabled={count === 0}
<ExportIcon className="h-6 w-6 mr-2"/> >
<ExportIcon className="h-6 w-6 mr-2" />
{t('export')} {t('export')}
</button> </button>
<button <button
key="reset" key="reset"
onClick={() => props.unsetGist(['layouts', 'printingLayout'])} onClick={() => props.unsetGist(['layouts', 'printingLayout'])}
className="btn btn-primary btn-outline"> className="btn btn-primary btn-outline"
<ClearIcon className="h-6 w-6 mr-2"/> >
<ClearIcon className="h-6 w-6 mr-2" />
{t('reset')} {t('reset')}
</button> </button>
</div> </div>
@ -62,22 +72,25 @@ const PrintLayoutSettings = props => {
name="pageMargin" name="pageMargin"
/> />
<div className="text-center"> <div className="text-center">
<span className="text-secondary"> <span className="text-secondary">{props.layoutSettings.margin}mm</span>
{props.layoutSettings.margin}mm
</span>
</div> </div>
<button <button
title={t('reset')} title={t('reset')}
className="btn btn-ghost btn-xs text-accent mx-2" className="btn btn-ghost btn-xs text-accent mx-2"
disabled={props.layoutSettings.margin == 10} disabled={props.layoutSettings.margin == 10}
onClick={() => setMargin({target: {value: 10}})} onClick={() => setMargin({ target: { value: 10 } })}
> >
<ClearIcon /> <ClearIcon />
</button> </button>
</label> </label>
<label htmlFor="coverPage" className="label"> <label htmlFor="coverPage" className="label">
<span className="mr-2">{t('coverPage')}</span> <span className="mr-2">{t('coverPage')}</span>
<input type="checkbox" className="toggle toggle-primary" checked={props.layoutSettings.coverPage} onChange={setCoverPage}/> <input
type="checkbox"
className="toggle toggle-primary"
checked={props.layoutSettings.coverPage}
onChange={setCoverPage}
/>
</label> </label>
</div> </div>
<div className="flex flex-row font-bold items-center px-0 text-xl"> <div className="flex flex-row font-bold items-center px-0 text-xl">
@ -87,7 +100,9 @@ const PrintLayoutSettings = props => {
<RightIcon /> <RightIcon />
<span className="ml-2">{cols}</span> <span className="ml-2">{cols}</span>
<span className="mx-6 opacity-50">|</span> <span className="mx-6 opacity-50">|</span>
<div className="rotate-90"><RightIcon /></div> <div className="rotate-90">
<RightIcon />
</div>
<span className="text-xl ml-2">{rows}</span> <span className="text-xl ml-2">{rows}</span>
</div> </div>
</div> </div>

View file

@ -118,7 +118,7 @@ const WorkbenchWrapper = ({ app, design, preload = false, from = false, layout =
const layout = gist.layouts?.[gist._state.view] || gist.layout || true const layout = gist.layouts?.[gist._state.view] || gist.layout || true
// hand it separately to the design // hand it separately to the design
draft = new design({ ...gist, layout }) draft = new design({ ...gist, layout })
console.log({ draft, design }) console.log({ draft, design, gist })
//draft.__init() //draft.__init()
// add theme to svg renderer // add theme to svg renderer