def testPDFImport(): path = getResourcesPath() + "/templates/test.idml" pdfpath = getResourcesPath() + "/templates/test.pdf" with idml.IDMLPackage(path) as idml_file: with idml_file.import_pdf(pdfpath, at="/Root/modules/module[0]") as f: f.export_xml()
def testSass(): import sass # Testing Sass. css = sass.compile(string='a { b { color: blue; } }') print(css) path = getResourcesPath() + '/templates/test.scss' import os.path print(os.path.exists(path)) css = sass.compile(filename=path) print(css) #test_scss = open('test.scss', 'w') import os, os.path for f in ('css', 'sass'): if not os.path.exists(f): os.mkdir(f) shutil.copy(path, 'sass') sass.compile(dirname=('sass', 'css'), output_style='compressed') with open('css/test.css') as example_css: print(example_css) # Export with HtmlBuilder. from pagebot.contexts.builders.htmlbuilder import HtmlBuilder hb = HtmlBuilder() print(hb) hb.compileScss(path, cssPath='css/testHtmlBuilder.css')
def testIDML(): path = getResourcesPath() + "/templates/template.idml" pkg = idml.IDMLPackage(path) print(pkg.font_families) l = [e.get("Name") for e in pkg.font_families] print(l) print(pkg.spreads) print(pkg.stories) xml = pkg.xml_structure from lxml import etree s = etree.tostring(xml, pretty_print=True) print(s)
def hyphenatedWords(language=DEFAULT_LANGUAGE): u"""Answer the dictionary of hyphenated words for this language (default is English).""" if language not in languages: # Not initialized yet, try to read. path = getResourcesPath() + '/languages/%s.txt' % language if os.path.exists(path): languages[language] = words = {} f = codecs.open(path, mode="r", encoding="utf-8") hyphenatedLines = f.read().split('\n') f.close() for line in hyphenatedLines: if line.startswith('#'): continue words[line.replace('-', '')] = line return languages.get(language)
def drawColorBars(self, e, origin): """Draw the color bars for offset printing color calibration. """ # TODO Get this to work for content of the parameter set. showColorBars = e.showColorBars or (e.isPage and self.showColorBars) if not showColorBars: return # Nothing to do. context = self.context ox, oy = point2D(origin) # TODO: Add more types of color bars and switch from scaling PDF to drawing them by script if ECI_GrayConL in showColorBars: path = getResourcesPath() + '/' + ECI_GrayConL if COLORBAR_LEFT in showColorBars: context.image(path, p=(ox - self.pl + pt(3), oy), h=e.h) if COLORBAR_RIGHT in showColorBars: # TODO: Does not generate the right position? context.image(path, p=(ox + e.w + self.pr * 2 / 3, oy), h=e.h)
def testContext(context): print(context) print(context.__dict__['b']) #for key, value in context.__dict__.items(): # print(' * %s: %s' % (key, value)) try: context.frameDuration(1) context.newDrawing() context.newPage(w=W, h=H) context.fill(f) context.stroke(s) x, y = getRandom() context.rect(x, y, 100, 100) x, y = getRandom() context.oval(x, y, 100, 100) x, y = getRandom() context.circle(x, y, 100) bla = context.newString('BabelString No Style') print(isinstance(bla, BabelString)) x, y = getRandom() context.text(bla, (x, y)) x, y = getRandom() context.text('plain string', (x, y)) style = {'font': 'Helvetica', 'textFill': f} bla = context.newString('Babel String with Style', style=style) x, y = getRandom() context.text('bla2', (x, y)) x, y = getRandom() context.text(bla, (x, y)) x, y = getRandom() path = getResourcesPath() + "/images/cookbot1.jpg" context.image(path, (x, y), w=100, h=100) # TODO: # - test Bézier path # - test glyph path # ... context.saveImage('_export/%s.pdf' % context.name) except Exception as e: print(traceback.format_exc())
def makeDocument(): """Make a new document.""" #W = H = 120 # Get the standard a4 width and height in points. W = PageSize H = PageSize # Hard coded SQUARE and GUTTE, just for simple demo, instead of filling padding an columns in the root style. # Page size decides on the amount squares that is visible. # Page padding is centered then. sqx = int( W / (SQUARE + GUTTER)) # Whole amount of squares that fit on the page. sqy = int(H / (SQUARE + GUTTER)) # Calculate centered paddings for the amount of fitting squares. # Set values in the rootStyle, so we can compare with column calculated square position and sizes. #rs['colH'] = rs['colW'] = SQUARE # Make default colW and colH square. #padX = (W - sqx*(SQUARE + GUTTER) + GUTTER)/2 my = (H - sqy * (SQUARE + GUTTER) + GUTTER) / 2 doc = Document(w=W, h=H, originTop=False, title='Color Squares', autoPages=1) view = doc.getView() view.padding = 0 # Aboid showing of crop marks, etc. view.showOrigin = True # Get list of pages with equal y, then equal x. #page = doc[1][0] # Get the single page from te document. page = doc.getPage( 1) # Get page on pageNumber, first in row (this is only one now). page.name = 'This is a demo page for floating child elements' page.padding = PagePadding page.gutter3D = GUTTER # Set all 3 gutters to same value path = getResourcesPath() + '/images/cookbot10.jpg' img = newImage( path, padding=0, parent=page, conditions=( Bottom2Bottom(), Fit2Width(), SolveBlock(), #Shrink2BlockBottom() ), yAlign=BOTTOM, fill=color(0, 1, 0, 0.3), stroke=color(1, 0, 0), scaleImage=False) # Give parent on creation, to have the css chain working. # Caption falls through the yr2 (with differnt z) and lands on yr1 by Float2SideBottom() fs = doc.context.newString('Captions float below the image', style=dict(font='Verdana', fontSize=20, textFill=color(1))) cap = newTextBox( fs, name='Caption', parent=img, z=0, conditions=[Fit2Width(), Float2Top()], padding=4, font='Verdana', yAlign=TOP, fontSize=9, textFill=color(1), strokeWidth=pt(0.5), fill=color(0, 0, 1, 0.3), stroke=color(0, 0, 1), ) score = page.solve() if score.fails: print(score.fails) print('Image size', img.w, img.h) print('Image file size', img.iw, img.ih) # TODO: Should not be pt(0, 0) for e in img.elements: print('Element', e) return doc # Answer the doc for further doing.
from pagebot.toolbox.color import color from pagebotcocoa.apps.baseapp import BaseApp from pagebotcocoa.contexts.drawbot.drawbotcontext import DrawBotContext from drawBot.ui.drawView import DrawView ADD_MENU = True context = DrawBotContext() fontRegular = findFont('PageBot-Regular') fontBold = findFont('PageBot-Bold') redColor = color('red') headStyle = dict(font=fontRegular, fontSize=pt(4)) MD_SAMPLE_PATH = getResourcesPath() + '/texts/SAMPLE.md' UNTITLED_PUBLICATION = 'Untitled Publication #%d' MENUS = ( ('File', 100, 'fileMenu', ( ('New publication', 'newPublication'), ('New page', 'newPage'), ('Open...', 'openPublication'), ('Close', 'closePublication'), ('Save', 'savePublication'), ('Save as...', 'saveAsPublication'), ('Print...', 'printPublication'), ('Export...', 'exportPublication'), ('Quit', 'quitApp'), )), ('Edit', 100, 'editMenu', (
# # Supporting usage of DrawBot, www.drawbot.com # Supporting usage of Flat, https://github.com/xxyxyz/flat # ----------------------------------------------------------------------------- # # fontpaths.py # import os from pagebot.toolbox.transformer import path2FontName from pagebot import getResourcesPath from pagebot.style import DEFAULT_FONT_PATH # P A T H S TEST_FONTS_PATH = getResourcesPath() + '/testfonts' # Dictionary with all available font paths on the platform, key is the single file name. FONT_PATHS = {} def getTestFontsPath(): u"""Answer the path of the PageBot test fonts.""" return TEST_FONTS_PATH def getFontPathOfFont(font, default=None): u"""Answer the path that is source of the given font name. If the path is already a valid font path, then aswer it unchanged. Answer None if the font cannot be found. >>> from pagebot.fonttoolbox.objects.font import findFont >>> font = findFont('Roboto-Regular')
from pagebot import getContext from pagebot.constants import A4 from pagebot.elements import * from pagebot.conditions import * context = getContext() W, H = A4 M = pt(8) # Margin between the images EXPORT_PATH = '_export/CacheScaledImage.pdf' if __name__ == '__main__': # Define the path where to find the example image. path = getResourcesPath() + "/images/cookbot1.jpg" # Use the standard DrawBot function to get the width/height of the image from the file. doc = Document( w=W, h=1.35 * H, originTop=False, context=context) # New simple document with default padding. page = doc[1] # Get first (and only) automatic page. factor = 1 # Incremental scale division factor of the image width. for n in range(12): # Stop before they become invisible small # Create a range of scaled imaged that try to fit by floating conditions. newImage(path, w=page.pw / factor, mr=M, mb=M, parent=page,
def testContext(context): # TODO: # - test elements # - test shadow, gradient, # ... sq = 100 x = 0 y = 0 print('Context', context) doc = Document(w=W, h=H, context=context, autoPages=1) context.frameDuration(1) context.newDrawing() context.newPage(w=W, h=H) context.text('default size string without style', pt(x, y)) y += sq context.fontSize(sq) context.text('%spt size string without style' % sq, pt(x, y)) y += sq bs = context.newString('BabelString No Style') print(bs.style) #print(bs.style.get('font')) #print(bs.style.get('fontSize')) #print(bs.style.get('fallbackFont')) context.strokeWidth(1) w0, h0 = context.textSize(bs) context.text(bs, pt(x, y)) print('String size is %dx%d' % (w0, h0)) y += sq fontName = 'Roboto-Black' font = findFont(fontName) style = {'font': font.path, 'textFill': f} bs = context.newString('Babel String with Style', style=style) print(bs.style) #print(bs.style.get('font')) #print(bs.style.get('fallbackFont')) context.text(bs, pt(x, y)) w0, h0 = context.textSize(bs) print('String size is %dx%d' % (w0, h0)) x = 2 * sq y = 0 path = getResourcesPath() + "/images/cookbot1.jpg" # Sloooow. #context.image(path, p=pt(x, y), w=pt(100), h=pt(100)) y += sq context.fill(f) context.stroke(s) context.rect(x, y, pt(sq), pt(sq)) y += sq context.circle(x + 0.5 * sq, y + 0.5 * sq, 0.5 * pt(sq)) y += sq context.oval(x, y, pt(sq), 0.5 * pt(sq)) y += sq glyphName = 'Q' glyph = font[glyphName] context.translate(2 * sq, sq) context.scale(0.1) context.drawGlyphPath(glyph) path = '_export/%s-%s.pdf' % ('Contexts', context.name) context.saveImage(path) print('Saved %s' % path)
def makeDocument(): """Make a new document.""" doc = Document(w=PageSize, h=PageSize, originTop=False, autoPages=1) view = doc.getView() view.padding = 10 # Don't show cropmarks and such. view.showCropMarks = True view.showOrigin = ShowOrigin view.showDimensions = False view.showElementInfo = ShowElementInfo page = doc[1] # Get the single page from te document. # Hard coded padding, just for simple demo, instead of # filling padding an columns in the root style. page.margin = 0 page.padding = SQ pageArea = PageSize - 2 * SQ print(PageSize, pageArea, SQ) # Make new container for adding elements inside with alignment. newRect(z=10, w=pageArea, h=pageArea, fill=color(0.8, 0.8, 0.8, 0.4), parent=page, margin=0, padding=0, yAlign=MIDDLE, xAlign=CENTER, stroke=noColor, conditions=(Center2Center(), Middle2Middle())) fontSize = RedHeight / 3 fs = doc.context.newString('Headline in red box.', style=dict(textFill=whiteColor, fontSize=fontSize, leading=fontSize, font='LucidaGrande')) newTextBox(fs, z=0, w=RedWidth, h=RedHeight, name='RedRect', parent=page, fill=color(1, 0.1, 0.1), yAlign=TOP, padding=4, conditions=(Center2Center(), Top2Top())) if not hasattr(scriptGlobals, 'blurbText'): scriptGlobals.blurbText = blurb.getBlurb('article_summary', noTags=True) fs = doc.context.newString('Headline of formatted text.\n', style=dict(font='LucidaGrande-Bold', fontSize=12, leading=14, textFill=blackColor)) fs += doc.context.newString(scriptGlobals.blurbText, style=dict(font='LucidaGrande', fontSize=10, leading=12, textFill=blackColor)) newTextBox(fs, z=0, w=YellowWidth, h=YellowHeight, parent=page, padding=4, fill=0.7, conditions=(Left2Left(), Float2Top())) path = getResourcesPath() + 'cookbot10.jpg' newImage(path, z=0, w=BlueWidth, parent=page, fill=0.7, padding=8, conditions=(Right2Right(), Float2Top())) newRect(z=0, w=BlueWidth, h=20, parent=page, fill=0.2, conditions=(Fit2Width(), Float2Top())) score = page.solve() if score.fails: print('Condition fails', score.fails) return doc # Answer the doc for further doing.
# from pagebot import getContext from pagebot import getResourcesPath from pagebot.fonttoolbox.objects.font import findFont from pagebot.document import Document from pagebot.elements import * # Import all types of page-child elements for convenience from pagebot.toolbox.color import color from pagebot.toolbox.units import em, p, pt from pagebot.conditions import * # Import all conditions for convenience. from pagebot.constants import GRID_COL_BG, GRID_ROW_BG, GRID_SQR_BG, LANGUAGE_EN context = getContext( ) # Get the context that we are running in (e.g. DrawBotContext = DrawBot) TEXT_PATH = getResourcesPath() + "/texts/TEST.md" W, H = pt(1500, 1000) # Document size PADDING = pt(100) # Page padding on all sides G = p(2) # 2 Pica gutter PW = W - 2 * PADDING # Usable padded page width PH = H - 2 * PADDING # Usable padded page height CW = (PW - G) / 3 # Column width CH = PH # Hard coded grid for 3 columns, will be automatic in later examples. GRIDX = ((CW, G), (CW, G), (CW, G)) GRIDY = ((CH, 0), ) # No division in vertical grid. BASELINE = G NUM_PAGES = 3
# # Supporting DrawBot, www.drawbot.com # Supporting Flat, xxyxyz.org/flat # ----------------------------------------------------------------------------- # # BinaryPNG.py # # Shows how to read and write a PNG image as a binary file. # from pagebot.contexts.platform import getContext from pagebot import getResourcesPath import os, os.path context = getContext() imagePath = getResourcesPath() + "/images/peppertom_lowres_398x530.png" with open(imagePath, "rb") as binary_file: # Read the whole file at once data = binary_file.read() #mutable_bytes = bytearray(data) #print(len(mutable_bytes)) if not os.path.exists('_export'): os.mkdir('_export') newFile = open("_export/test.png", "wb") newFile.write(data) context.newDocument(1100, 1100) context.newPage(1100, 1100)
# ImageObject filters. # from pagebot import getResourcesPath from pagebot.fonttoolbox.objects.family import getFamily from pagebot.style import TOP, BOTTOM, A4 from pagebot.conditions import * from pagebot.elements import * from pagebot.document import Document from pagebot.toolbox.color import color # Document is the main instance holding all information about the # document together (pages, styles, etc.) W, H = A4 IMAGE_PATH = getResourcesPath() + '/images/peppertom_lowres_398x530.png' family = getFamily('Roboto') font = family.findFont(weight=400) fontItalic = family.findFont(weight=400, italic=True) GUTTER = 8 # Distance between the squares. SQUARE = 10 * GUTTER # Size of the squares CW = 170 M = (W - 3*CW)/2 PADDING = M, M, M, M FILTER_TYPES = { } # Export in _export folder that does not commit in Git. Force to export PDF.
# # 06_TraceImage.py # # Trace a halftone image to vectors. # from pagebot.elements.paths.pagebotpath import PageBotPath from pagebot import getResourcesPath from pagebot.toolbox.units import p from pagebot.toolbox.color import color from pagebot import getContext # Get the context (e.g. DrawBot) to call for conversion method context = getContext() # Get the path of the image from PageBot resources imagePath = getResourcesPath() + '/images/cookbot10.jpg' # Create a PageBotPath wrapper instance, that include a Context.BezierPath path = PageBotPath(context=context) # Trace the image. # traceImage(path, threshold=0.2, blur=None, invert=False, turd=2, tolerance=0.2, offset=None) # Convert a given image to a vector outline. # Optionally some tracing options can be provide: # # threshold (0.2): the threshold used to bitmap an image # blur (None): the image can be blurred # invert (False): invert to the image # turd (2): the size of small turd that can be ignored # tolerance (0.2): the precision tolerance of the vector outline # offset (None): add the traced vector outline with an offset to the BezierPath
#!/usr/bin/env python3 # ----------------------------------------------------------------------------- # Copyright (c) 2016+ Buro Petr van Blokland + Claudia Mens # www.pagebot.io # # P A G E B O T # # Licensed under MIT conditions # # Supporting DrawBot, www.drawbot.com # Supporting Flat, xxyxyz.org/flat # ----------------------------------------------------------------------------- # # 01_SpecimenApp.py # from pagebot import getResourcesPath from pagebot.apps.specimenapp import SpecimenApp fontPath = getResourcesPath() + '/testfonts/fontbureau' app = SpecimenApp(fontPath)