示例#1
0
def makeSite(siteDescription, styles, viewId):
    doc = Site(viewId=viewId, autoPages=len(siteDescription), styles=styles)
    view = doc.view
    view.resourcePaths = ('css', 'fonts', 'images', 'js')
    view.jsUrls = (URL_JQUERY, URL_MEDIA, 'js/main.js')
    # SiteView will automatic generate css/style.scss.css from assumed css/style.scss
    if USE_SCSS:
        view.cssUrls = ('fonts/webfonts.css', 'css/normalize.css',
                        'css/style.scss.css')
    else:
        view.cssUrls = ('fonts/webfonts.css', 'css/normalize.css',
                        'css/style-org.css')

    # Make the all pages and elements of the site as empty containers
    makePages(doc, siteDescription)
    # By default, the typesetter produces a single Galley with content and code blocks.

    t = Typesetter(doc.context)
    galley = t.typesetFile(MD_PATH)
    # Create a Composer for this document, then create pages and fill content.
    composer = Composer(doc)
    # The composer executes the embedded Python code blocks that direct where context should go.
    # by the HtmlContext.
    composer.compose(galley)

    doc.solve(
    )  # Solve all layout and float conditions for pages and elements.

    return doc
示例#2
0
def makeDocument():

    doc = Document(originTop=False, w=W, h=H, autoPages=1)
    doc.addStyle('h1', dict(textFill=0))
    doc.addStyle('h2', dict(textFill=0))
    doc.addStyle('p', dict(textFill=0))

    page = doc[0]  # Get the first/single page of the document.
    page.padding = 40  # TODO: order if 4 values?

    # Make rect as page element centered with centered origin.
    conditions = [Fit()]

    g = Galley(parent=page, conditions=conditions, textFill=0)
    ts = Typesetter(doc, g)
    print ts
    ts.typesetFile(markdownPath)

    # Solve the layout conditions of the red rectangle.
    # Show if one of the conditions failed to solve.
    score = page.solve()
    if score.fails:
        print 'Failed conditions', score.fails

    # Set the view parameters for the required output.
    view = doc.getView()
    view.padding = 0  # Make view padding to show crop marks and frame
    view.showPageFrame = True  # Show frame of the page in blue
    #view.showPagePadding = True
    view.showPageCropMarks = True  # Show crop marks

    return doc
示例#3
0
def makeSite(styles, viewId):
    site = Site(styles=styles)
    doc = site.newDocument(viewId=viewId,
                           autoPages=1,
                           defaultImageWidth=MAX_IMAGE_WIDTH)

    doc.theme = theme

    view = doc.view
    view.resourcePaths = ('css', 'fonts', 'images', 'js')
    view.jsUrls = (
        URL_JQUERY,
        #URL_MEDIA,
        'js/sitemain.js',
        'js/jquery.bbslider.min.js')

    # Generate css by mapping theme.mood on cssPy
    cssPath = 'css/nanostyle_py.css'
    doc.context.b.writeCss(cssPath, cssPy % theme.mood)

    view.cssUrls = (
        'css/jquery.bbslider.css',
        'fonts/webfonts.css',
        'css/normalize.css',
        cssPath,
    )

    # Make the all pages and elements of the site as empty containers, that then can
    # be selected and filled by the composer, using the galley content.
    # Of the MarkDown text can decide to create new elements inside selected elements.
    template = makeTemplate(doc)

    page = doc[1]
    page.applyTemplate(template)  # Copy element tree to page.

    # By default, the typesetter produces a single Galley with content and code blocks.
    t = Typesetter(doc.context)
    galley = t.typesetFile(MD_PATH)

    # Create a Composer for this document, then create pages and fill content.
    composer = Composer(doc)

    # The composer executes the embedded Python code blocks that indicate where content should go.
    # by the HtmlContext. Feedback by the code blocks is added to verbose and errors list
    targets = dict(doc=doc, page=page, template=template)
    composer.compose(galley, targets=targets)

    if VERBOSE:
        if targets['verbose']:
            print('Verbose\n', '\n'.join(targets['verbose']))
        # In case there are any errors, show them.
        if targets['errors']:
            print('Errors\n', '\n'.join(targets['errors']))

    # Find the navigation elements and fill them, now we know all the pages.
    makeNavigation(doc)

    return doc
示例#4
0
    def build(self):
        # Create an unbound Typesetter instance (trying to find a Book
        # (inheriting from Document) instance in one of the codeblock results.
        # If no Galley instance is supplied to the Typesetter, it will create one.
        t = Typesetter()
        # Parse the markdown content and execute the embedded Python code blocks.
        # The blocks, global defined variables and text content are in the
        # typesetter t.galley.
        t.typesetFile(MD_PATH)
        # The markdown document created a t.doc Document instance,

        # The typesetter produced a single Galley with content and code blocks.
        # Now use a composer (automatic "designer") to fit the pieces together.
        # Takes a galley as soruce and a document for target pages.
        #Composer().compose(t.galley, t.doc)

        # DEBUGGING Stuff
        if 0:  # Print some results of the typesetter
            # Typesetter found document definition inside content.
            print 'Book title:', t.doc.title, round(t.doc.w), round(t.doc.h)
            # Multiple code blocks found with identical identifier.
            # Added counter 'Views_0' to 'Views' to make it unique.
            print 'Found code blocks: %d' % len(t.codeBlocks.keys())
            #print t.galley.elements[0].text
            #page = t.doc[0]
            #print page.padding
            #print page.w, page.h

        if 0:  # Debugging, show the pages with their names.
            print t.doc.css('gridL')
            for templateName, template in t.doc.templates.items():
                print templateName, template.name
            for pn, pages in t.doc.getSortedPages():
                for page in pages:
                    print '\t', page, page.w, page.h, page.template.name
                    #page.isLeft(), page.isRight(), page.getGridColumns()

        # Views define the way documents are exported.
        # Add space for cropmarks and registrations marks
        view = t.doc.getView()
        view.padding = 30
        view.showPageNameInfo = True
        view.showPagePadding = False  # No need, as we are drawing the grid
        view.showPageCropMarks = True
        view.showPageRegistrationMarks = True
        view.showPageFrame = True
        view.showGrid = False

        view.style['viewGridStroke'] = (0, 0, 1)
        view.style['viewGridStrokeWidth'] = 0.5

        t.doc.solve()

        t.doc.export(EXPORT_PATH)
示例#5
0
    def typeset(self):
        u"""Take the composition descriptor of the Article and apply it to the document,
        by interpreting key words in the "free language" design talk and finding the 
        related functions to call.

        """
        if self.mdText:
            t = Typesetter(self.doc.context)
            tmpPath = '/tmp/PageBot-Article.xml'
            path = t.markDown2XmlFile(tmpPath, self.mdText)
            galley = t.typesetFile(path)
            os.remove(tmpPath)
示例#6
0
def makeDocument():
    u"""Demo page composer."""

    # Set some values of the default template (as already generated by the document).
    # Make squential unique names for the flow boxes inside the templates
    flowId0 = MAIN_FLOW+'0' 
    flowId1 = MAIN_FLOW+'1'
    flowId2 = MAIN_FLOW+'2'
    headlineId = 'headLine'
    
    # Template 2
    template = Template(w=W, h=H) # Create second template. This is for the main pages.
    # Add image containers to the page, that images + captions, within the defined space.
    newColRect(4, 0, 2, 3, parent=template, )  # Empty image element, cx, cy, cw, ch
    newColRect(0, 5, 2, 3, parent=template, )
    newColRect(2, 2, 2, 2, parent=template, )
    newColRect(4, 6, 2, 2, parent=template, )
    
    # In this simple example page, we won't have the headline run in the galley of the main text.
    # Create separate text box here to accommodate the headline.
    newColTextBox('', 0, 0, 4, 2, parent=template, eId=headlineId, fill=BOX_COLOR)

    # Make linked text box elemnents, where position and size is defined by columns.
    newColTextBox('', 0, 2, 2, 3, parent=template, eId=flowId0, nextBox=flowId1, nextPage=0, fill=BOX_COLOR)
    newColTextBox('', 2, 4, 2, 4, parent=template, eId=flowId1, nextBox=flowId2, nextPage=0, fill=BOX_COLOR)
    # Final column flow on the page does not link to next page. We want this demo one page only.
    newColTextBox('', 4, 3, 2, 3, parent=template, eId=flowId2, fill=BOX_COLOR)
    
    # Create new document with (w,h) and fixed amount of pages.
    # Make number of pages with default document size.
    # Initially make all pages default with template
    doc = Document(w=W, h=H, autoPages=2, template=template) 
 
    # Change template of page 1
    onePage = doc[0]
        
    # Create main Galley for this page, for pasting the sequence of elements.    
    g = Galley() 
    t = Typesetter(g, doc)                
    """
    blurbNames = (('h1', 'news_headline'), ('h2', 'article_ankeiler'))
    t.typesetFilibuster(blurbNames)
    
    c = Composer(doc)
    c.compose(g, onePage, headlineId)

    g = Galley() 
    t = Typesetter(doc, g)                
    blurbNames = (('h3', 'article_ankeiler'), ('h2', 'article_summary'), ('p', 'article'))
    t.typesetFilibuster(blurbNames)
    
    # Fill the main flow of text boxes with the ML-->XHTML formatted text. 
    c = Composer(doc)
    c.compose(g, onePage, flowId0)
    """
    return doc
示例#7
0
    def buildSample(self, doc):
        page = doc[1]
        theme = self.getTheme()
        if doc.view.showFrame:
            c = theme.mood.body_bgcolor.lessOpaque()
            newRect(parent=page, fill=c, conditions=[Fit2Sides()])

        # By default, the typesetter produces a single Galley with content and code blocks.
        t = Typesetter(doc.context)
        t.typesetFile(MD_SAMPLE_PATH)

        # Create a Composer for this document, then create pages and fill content.
        composer = Composer(doc)

        # The composer executes the embedded Python code blocks that indicate where content should go.
        # by the HtmlContext. Feedback by the code blocks is added to verbose and errors list
        targets = dict(pub=self, doc=doc, page=page)
        composer.compose(t.galley, targets=targets)

        """
        if doc.view.showGrid:
            c = theme.mood.body_color.lessOpaque()
            for n in range(len(doc.gridX)):
                colWidth = doc.gridX[n][0]
                if n:
                    conditions = [Left2Col(n), Fit2Height()]
                else:
                    conditions = [Left2Left(), Fit2Height()]
                newRect(parent=page, fill=c, w=colWidth, conditions=conditions)
        """

        """
        theme = self.getTheme()
        newTextBox(str(theme.mood.name), style=headStyle, parent=grp, conditions=[Fit2Width(), Top2Top()])
        for colorName in sorted(theme.mood.palette.colorNames):
            color = theme.mood.palette[colorName]
            newRect(parent=grp, w=32, h=32, fill=color, conditions=[Right2Right(), Float2Top(), Float2Left()])
        """
        page.solve()
示例#8
0
MD_PATH = u"DesignDesignSpace.md"

# Export in _export folder that does not commit in Git. Force to export PDF.
# The .html and .css extensions triggers the HtmlBuilder and CssBuilder to be used for file export.
# If the MAMP server application not installed, a browser is opened on their website to download it.
MAMP_PATH = '/Applications/MAMP/htdocs/'
MAMP_PAGEBOT_PATH = MAMP_PATH + 'pagebot/designdesignspace/'
EXPORT_PATH_HTML = MAMP_PAGEBOT_PATH + 'index.html'
EXPORT_PATH_CSS = MAMP_PAGEBOT_PATH + 'main.css'
MAMP_LOCAL_URL = 'http://localhost:8888/pagebot/examplewebsite/index.html'
MAMP_SHOP_URL = 'https://www.mamp.info/en/'  # In cade MAMP does not exist, open on their website to download and install.

# Create an unbound Typesetter instance (trying to find a Poster
# (inheriting from Document) instance in one of the codeblock results.
# If no Galley instance is supplied to the Typesetter, it will create one.
t = Typesetter()
# Parse the markdown content and execute the embedded Python code blocks.
# The blocks, global defined variables and text content are in the
# typesetter t.galley.
t.typesetFile(MD_PATH)
#print t.codeBlocks
# The typesetter produced a single Galley with content and code blocks.
# Now use a composer (automatic "designer") to fit the pieces together.
# Takes a galley as soruce and a document for target pages.
Composer().compose(t.galley, t.doc)

tmp = Template(w=t.doc.w, h=t.doc.h, name='DEMO Page', gridY=[(None, 0)])
t.doc.demo = newPlacer(parent=tmp,
                       conditions=[Left2Col(1), Bottom2Row(0)],
                       name='Title',
                       h=200)
示例#9
0
Above some highlights of the current state of PageBot.

#### Heading #4

Above some highlights of the current state of PageBot.[S]
Above some highlights of the current state of PageBot.

""".replace('[S]\n', ' ')

page = doc[1]
page.baselineGrid = LEADING
page.baselineGridStart = page.pt
page.showBaselineGrid = [BASE_LINE_BG, BASE_INDEX_LEFT]
page.baselineColor = color(1, 0, 0)

t = Typesetter(doc.context, styles=styles)
galley = t.typesetMarkdown(s)


tb1 = galley.elements[0]
tb1.fill = 0.95
tb1.baselineColor = color(0.5)
tb1.parent = page
tb1.w = CW+CW+G
tb1.h = H
tb1.conditions = (Right2Right(), Top2Top(), Baseline2Grid(index=3))


s = doc.context.newString('Ha', style=titleStyle)
tb2 = newTextBox(s, parent=page, w=CW, 
    conditions=(Left2Left(), Top2Top(), Baseline2Grid()))
示例#10
0
    #URL_MEDIA, 
    'js/sitemain.js', 
    'js/jquery.bbslider.min.js'
)
# SiteView will automatic generate css/style.scss.css from assumed css/style.scss
view.cssUrls = (
    'fonts/webfonts.css', 'css/normalize.css', 
    #'css/nanostyle_css.py' # Will automatic call conversion by the theme.mood.
    'css/nanostyle.css', 
    #'css/style-org.css', 
    'css/jquery.bbslider.css'
)

# Read the markdown file, where all elements (embedded code blocks) are pasted
# on a galley element, in sequential order. No interpreting takes place yet.
t = Typesetter(context, styles=styles)
galley = t.typesetFile(MARKDOWN_PATH)

# Make a simplet template: one page with one column.
page = doc[1] # Get the first/single page of the document.
page.padding = PADDING # Set the padding of this page.

# Make a text box, fitting the page padding on all sides.
# The name "Box" is used to identiify the box that MarkDown text goes into.
newTextBox(parent=page, name='Box', conditions=[Fit()])

page.solve() # Solve the fitting condition.

# Create the Composer instance that will interpret the Typesetter galley.
composer = Composer(doc)
示例#11
0
def makeDocument():
    u"""Demo Bitcount Reference composer."""

    # Set some values of the default template (as already generated by the document).
    # Make squential unique names for the flow boxes inside the templates
    coverTitleId = 'coverTitleId'  # To find the placement of the cover title.
    coverAuthorId = 'coverAuthorId'  # Find the placement for the author name.
    tocId = 'toc'  # Id of target textBox, containing the table of content.
    flowId1 = MAIN_FLOW + '1'
    flowIds = [flowId1]  # Names of boxes that contain footnote text in flow.
    footnotesId = 'footnotes'  # Id of target textBox containing footnotes per page.
    literatureIndexId = 'literatureIndex'
    imageIndexId = 'imageIndex'
    pageNumberId = 'pageNumberId'

    # Template for Cover page
    templateCover = Template()  # Create new template
    newColTextBox(0, 0, w=W, h=H, fill=(1, 0, 0), parent=templateCover)
    # Placement of first <h1> in the Galley, holding the Thesis title.
    newColTextBox('Title of the page',
                  1,
                  1,
                  6,
                  5,
                  eId=coverTitleId,
                  fill=BOX_COLOR,
                  parent=templateCover)
    # Placement of first <h4> in the Galley, holding the author name(s)
    newColTextBox('Subhead of the page',
                  1,
                  8,
                  6,
                  5,
                  eId=coverAuthorId,
                  fill=BOX_COLOR,
                  parent=templateCover)

    # Template for Table of Content
    templateToc = Template()  # Create template for Table of Content
    newColTextBox('\nTable of Content',
                  3,
                  0,
                  4,
                  1,
                  fill=BOX_COLOR,
                  fontSize=32,
                  parent=templateToc)
    newColTextBox('',
                  3,
                  1,
                  4,
                  8,
                  eId=tocId,
                  fill=BOX_COLOR,
                  parent=templateToc)

    # Template for literature reference index.
    templateLiteratureIndex = Template(
    )  # Create template for Table of Content
    newColTextBox('\nLiterature index',
                  3,
                  0,
                  4,
                  1,
                  fill=BOX_COLOR,
                  fontSize=32,
                  parent=templateLiteratureIndex)
    newColTextBox('',
                  3,
                  1,
                  4,
                  8,
                  eId=literatureIndexId,
                  fill=BOX_COLOR,
                  parent=templateLiteratureIndex)

    # Template for image reference index.
    templateImageIndex = Template()  # Create template for Table of Content
    newColTextBox('\nImage index',
                  3,
                  0,
                  4,
                  1,
                  fill=BOX_COLOR,
                  fontSize=32,
                  parent=templateImageIndex)
    newColTextBox('',
                  3,
                  1,
                  4,
                  8,
                  eId=imageIndexId,
                  fill=BOX_COLOR,
                  parent=templateImageIndex)

    # Template 1
    template1 = Template()  # Create template of main size. Front page only.
    # Create empty image place holders. To be filled by running content on the page.
    # In this templates the images fill the left column if there is a reference on the page.
    newColPlacer(0, 0, 3, 3,
                 parent=template1)  # Empty image element, cx, cy, cw, ch
    newColPlacer(0, 3, 3, 3, parent=template1)
    newColPlacer(0, 6, 3, 3, parent=template1)
    # Create linked text boxes. Note the "nextPage" to keep on the same page or to next.
    newColTextBox('ABC',
                  3,
                  0,
                  4,
                  9,
                  eId=flowId1,
                  nextBox=flowId1,
                  nextPage=1,
                  fill=BOX_COLOR,
                  parent=template1)
    newColTextBox('',
                  3,
                  9,
                  3,
                  2,
                  eId=footnotesId,
                  fill=BOX_COLOR,
                  parent=template1)
    # Create page number box. Pattern pageNumberMarker is replaced by FormattedString of actual page number.
    # Mark the text box, so we can find it back later.
    newColTextBox(['pageIdMarker'],
                  6,
                  9,
                  1,
                  1,
                  eId=pageNumberId,
                  font=BOOK,
                  fontSize=12,
                  fill=BOX_COLOR,
                  xAlign=RIGHT,
                  parent=template1)

    # Create new document with (w,h) and fixed amount of pages.
    # Make number of pages with default document size.
    # Initially make all pages default with template2
    doc = Document(autoPages=5, template=template1)

    rs = doc.getRootStyle()

    rs['openTypeFeatures'] = dict(zero=Slashed_Zero,
                                  smcp=Smallcaps,
                                  c2sc=Caps_As_Smallcaps,
                                  ss08=Italic_Shapes,
                                  ss07=Condensed,
                                  ss01=Extended_Ascenders,
                                  ss02=Extended_Capitals,
                                  ss03=Extended_Descenders,
                                  ss04=Contrast_Pixel,
                                  ss09=Alternative_g,
                                  onum=LC_Figures)

    # Cache some values from the root style that we need multiple time to create the tag styles.
    fontSize = rs['fontSize']
    leading = rs['leading']
    rLeading = rs['rLeading']
    listIndent = rs['listIndent']
    language = rs['language']

    # Add styles for whole document and text flows.
    # Note that some values are defined here for clarity, even if their default root values
    # are the same.
    doc.newStyle(name='chapter', font=BOOK)
    doc.newStyle(name='title', fontSize=3 * fontSize, font=BOLD)
    doc.newStyle(name='subtitle', fontSize=2.6 * fontSize, font=BOOK_ITALIC)
    doc.newStyle(name='author',
                 fontSize=2 * fontSize,
                 font=BOOK,
                 fill=(1, 0, 0))
    doc.newStyle(name='h1',
                 fontSize=7 * fontSize,
                 font=SEMIBOLD_CONDENSED,
                 fill=(1, 0, 0),
                 leading=7.2 * fontSize,
                 tracking=H1_TRACK,
                 prefix='',
                 postfix='\n')
    doc.newStyle(name='h2',
                 fontSize=1.5 * fontSize,
                 font=SEMIBOLD_CONDENSED,
                 fill=0,
                 leading=1.6 * fontSize,
                 rLeading=0,
                 rTracking=H2_TRACK,
                 prefix='\n',
                 postfix='\n',
                 paragraphTopSpacing=U)
    doc.newStyle(name='h3',
                 fontSize=1.1 * fontSize,
                 font=MEDIUM,
                 fill=0,
                 paragraphTopSpacing=2 * U,
                 paragraphBottomSpacing=U,
                 leading=leading,
                 rLeading=0,
                 rNeedsBelow=2 * rLeading,
                 rTracking=H3_TRACK,
                 prefix='\n',
                 postfix='\n')
    doc.newStyle(name='h4',
                 fontSize=1.1 * fontSize,
                 font=BOOK,
                 fill=0,
                 leading=leading,
                 rLeading=0,
                 rNeedsBelow=2 * rLeading,
                 rTracking=H3_TRACK,
                 paragraphTopSpacing=U,
                 paragraphBottomSpacing=U,
                 prefix='\n',
                 postfix='\n')

    # Spaced paragraphs.
    doc.newStyle(
        name='p',
        fontSize=fontSize,
        font=BOOK,
        fill=0.1,
        prefix='',
        postfix='\n',
        rTracking=P_TRACK,
        leading=14,
        rLeading=0,
        xAlign=LEFT,
        hyphenation=True,
        indent=0,
        firstLineIndent=2 * U,
        firstParagraphIndent=0)  # TODO: Make firstParagraphIndent to work.
    # Inline tags need to refined prefix and postfix as non-\n, otherwise they
    # will inherit these attributes from the parent <p>
    doc.newStyle(name='b', font=SEMIBOLD, prefix='', postfix='')
    doc.newStyle(name='em',
                 font=BOOK_ITALIC,
                 textFill=(1, 0, 0),
                 prefix='',
                 postfix='')
    doc.newStyle(name='hr', stroke=(1, 0, 0), strokeWidth=4)
    doc.newStyle(name='br',
                 postfix='\n')  # Simplest way to make <br/> show newline
    doc.newStyle(name='a', prefix='', postfix='')

    # Literature reference.
    doc.newStyle(name='literatureref', textFill=0.3, fontSize=fontSize - 1)

    # Footnote reference index.
    doc.newStyle(name='sup',
                 font=MEDIUM,
                 baselineShift=2,
                 prefix='',
                 postfix=' ',
                 fontSize=fontSize - 2)
    doc.newStyle(
        name='li',
        fontSize=fontSize,
        font=BOOK,
        rTracking=P_TRACK,
        leading=leading,
        hyphenation=True,
        # Lists need to copy the listIndex over to the regalar style value.
        tabs=[(listIndent, LEFT)],
        indent=listIndent,
        firstLineIndent=1,
        postfix='\n')
    doc.newStyle(name='ul', prefix='', postfix='')
    doc.newStyle(name='footnote',
                 fill=0,
                 fontSize=0.9 * fontSize,
                 font=BOOK,
                 rTracking=P_TRACK,
                 tabs=[(listIndent, LEFT)],
                 indent=listIndent,
                 firstLineIndent=1,
                 postfix='\n')

    # Image & captions
    doc.newStyle(
        name='img',
        stroke=0.3,
        fill=None,
        rTracking=P_TRACK,
        language=language,
        textFill=0.2,
        strokeWidth=1,
        leading=leading * 0.8,
        fontSize=0.8 * fontSize,
        font=BOOK_ITALIC,
        hyphenation=True,
        indent=0,
        firstLineIndent=0,
        # Use style['fill'] = transparant color as overlay on image.
    )

    # Generic document layout
    # Page 1    Cover
    # Page 2    Title
    # Page 3    Table of Content
    # Page 4+   Content  (footnotes are shown on the page of their reference)
    # Page -1   Alphabetical literature reference.

    # Change template of cover page.
    # Create filtered Galley for cover page.
    # See https://docs.python.org/2/library/xml.etree.elementtree.html#xpath-support
    # for XPath filter syntax.
    gTitle = Galley()
    t = Typesetter(doc, gTitle)
    #t.typesetFile(MD_PATH, style=dict(textFill=1, fontSize=80, font=MEDIUM, leading=84),
    #    xPath='h1')

    gAuthor = Galley()
    t = Typesetter(doc, gAuthor)
    #t.typesetFile(MD_PATH, style=dict(textFill=1, fontSize=24, font=MEDIUM),
    #    xPath='h4') # First one is the author

    coverPage = doc[1]
    coverPage.applyTemplate(templateCover)
    c = Composer(doc)
    #c.compose(gTitle, coverPage, coverTitleId)
    #c.compose(gAuthor, coverPage, coverAuthorId)

    # Change template of Table of Content page
    tocPage = doc[2]
    tocPage.applyTemplate(templateToc)

    mainPage = doc[3]

    # Create main Galley for this page, for pasting the sequence of elements.
    g = Galley()
    t = Typesetter(doc, g)
    t.typesetFile(MD_PATH)

    # Fill the main flow of text boxes with the ML-->XHTML formatted text.
    c = Composer(doc)
    c.compose(g, mainPage, flowId1)

    # Now all text is composed on pages, scan for the pages that contain footnotes.
    # TODO: This will be implemented a function inside Composer in a later version.
    # Assume the tocBox (Table of Content) to be available on the first page.
    literatureRefs = {}
    tocBox, (_, _) = tocPage[tocId]
    for pageId, page in sorted(doc.pages.items()):
        if page in (tocPage,
                    coverPage):  # Skip these for toc collect and footnotes.
            continue
        # Get page box for footnotes
        fnBox, (_, _) = page[footnotesId]
        assert fnBox is not None  # Otherwise there is a template error. Footnote box needs to exist.
        for flowId in flowIds:
            # BUG: Need to check if the marker was really found in the textbox area.
            # If it is part of the overflow, then it should not be found here.
            flow, _ = page[flowId]
            for marker, arguments in findMarkers(flow.fs):
                if marker == 'footnote':
                    footNoteIsInOverflow = False
                    # Process the foot note.
                    footnoteId = int(arguments)  # Footnode ids are numbers.
                    # @@@ Hack to check if the marker is in the overflow text.
                    # In that case, ignore it.
                    for overFlowMarker, overFlowArguments in findMarkers(
                            flow.getOverflow()):
                        # If this marker is a footnote and one that we are looking for,
                        # we can ignore it, because it is in the overflow part of the flow.fs
                        if overFlowMarker == 'footnote' and footnoteId == int(
                                overFlowArguments):
                            footNoteIsInOverflow = True
                            break
                    if not footNoteIsInOverflow:
                        # We found a footnote that is visible on this page and
                        # not in one of the overflow texts.
                        # Process the footnote id and content, usng the “footnote“ content style.
                        # We are re-using the typesetter here. This may become a separate typesetter, if this code
                        # becomes a method of the composer.
                        # TODO: Make this into Galley, in case footnote <p> has child nodes.
                        footnoteText = doc.context.newString(
                            '%d\t%s\n' %
                            (footnoteId, doc.footnotes[footnoteId]['p'].text),
                            page, t.getCascadedStyle(doc.getStyle('footnote')))
                        # Add the footnote content to the box (it may not be the first to be added.
                        fnBox.append(footnoteText)
                elif marker in ('h1', 'h2', 'h3',
                                'h4'):  # For now we want them all in the TOC
                    #doc.addToc(marker)
                    pass
                elif marker == 'literature':
                    # The "arguments" contains the refId, so we can find it in the collected literature references
                    # and then add this page number.
                    # @@@ TODO: check if reference marker is in overflow. Then ignore processing it.
                    doc.literatureRefs[int(arguments)]['pageIds'].append(
                        pageId)

    # Build the alphabetical literature reference page.
    # Scan the created pages for literature references and build an index on a new page.
    literatureIndexPage = doc.newPage(template=templateLiteratureIndex)
    # Make an alfabetic sorted list of name-->(reference, (pageNumber, ...))
    references = {}
    for refIndex, item in doc.literatureRefs.items():
        references[item['nodeId']] = item
    literatureRefBox = literatureIndexPage.getElement(literatureIndexId)
    for refId, item in sorted(references.items()):
        # Now we have a sorted list of reference items, we need to make it into a galley.
        # Several ways of doing it: Create MarkDown, HTML/XML or directly writing FormattedText.
        pageNumbers = []
        for pageNumber in item['pageIds']:
            pageNumbers.append( ` pageNumber `)
        literatureRefBox.append(u'%s – %s\n' % (refId, ', '.join(pageNumbers)))

        print refId, item['nodeId'], item['node'], item['p'], item['pageIds']

    # Build the alphabetical image reference page.
    # Scan the created pages for image references and build an index on a new page.
    imageIndexPage = doc.newPage(template=templateImageIndex)
    # Make an alfabetic sorted list of name-->(reference, (pageNumber, ...))
    references = {}
    for refIndex, item in doc.imageRefs.items():
        references[item['nodeId']] = item
    for imageRefId, item in sorted(references.items()):
        print imageRefId, item['nodeId'], item['node'], item['p'], item[
            'pageIds']

    # Set all pagenumbers and other page-based info
    for pageId, page in sorted(doc.pages.items()):
        for e in page.elements:
            if e.eId == pageNumberId:
                e.setText('%s' % pageId)
                break

    return doc
示例#12
0
    menuItem42 = MenuItem(parent=menu4, href='page4.html', label='menu item 4.2', current=False)
    
    menu5 = Menu(parent=menuItem5)
    menuItem51 = MenuItem(parent=menu5, href='page5.html', label='menu item 5.1', current=False)
    menuItem52 = MenuItem(parent=menu5, href='page5.html', label='menu item 5.2', current=False)
    
    hero = Hero(parent=page)
    
    content = Content(parent=page, fill='red')
    section = ColoredSection(parent=page)
    footer = Footer(parent=page)
    
# Create a Typesetter for this document, then create pages and fill content. 
# As no Galley instance is supplied to the Typesetter, it will create one,
# or put the current page/box variables to where the MarkDown file indicates.
t = Typesetter(doc, tryExcept=True, verbose=False)
# Parse the markdown content and execute the embedded Python code blocks.
# The blocks, global defined feedback variables and text content are in the 
# typesetter t.galley.
# By default, the typesetter produces a single Galley with content and code blocks.
# In this case it directly writes into the boxes on the Website template pages.
t.typesetFile(MD_PATH)

if DO_FILE:
    doc.export(EXPORT_PATH)
    os.system('open "%s/index.html"' % EXPORT_PATH)

elif DO_MAMP:
    # Internal CSS file may be switched of for development.
    view = doc.newView('Mamp')
示例#13
0
def makeDocument(rs):
    u"""Demo page composer."""

    # Set some values of the default template (as already generated by the document).
    # Make squential unique names for the flow boxes inside the templates
    flowId1 = MAIN_FLOW + '1'
    flowId2 = MAIN_FLOW + '2'
    flowId3 = MAIN_FLOW + '3'

    # Template 1
    template1 = Template(rs)  # Create template of main size. Front page only.
    # Show grid columns and margins if rootStyle.showGrid or rootStyle.showGridColumns are True
    template1.grid(rs)
    # Show baseline grid if rs.showBaselineGrid is True
    template1.baselineGrid(rs)
    # Create empty image place holders. To be filled by running content on the page.
    template1.cContainer(4, 0, 2, 4, rs)  # Empty image element, cx, cy, cw, ch
    template1.cContainer(0, 5, 2, 3, rs)
    # Create linked text boxes. Note the "nextPage" to keep on the same page or to next.
    template1.cTextBox(FS,
                       0,
                       0,
                       2,
                       5,
                       rs,
                       flowId1,
                       nextBox=flowId2,
                       nextPage=0,
                       fill=BOX_COLOR)
    template1.cTextBox(FS,
                       2,
                       0,
                       2,
                       8,
                       rs,
                       flowId2,
                       nextBox=flowId3,
                       nextPage=0,
                       fill=BOX_COLOR)
    template1.cTextBox(FS,
                       4,
                       4,
                       2,
                       4,
                       rs,
                       flowId3,
                       nextBox=flowId1,
                       nextPage=1,
                       fill=BOX_COLOR)
    # Create page number box. Pattern pageNumberMarker is replaced by actual page number.
    template1.cText(FS + rs['pageIdMarker'],
                    6,
                    0,
                    style=rs,
                    font=BOOK,
                    fontSize=12,
                    fill=BOX_COLOR)

    # Template 2
    template2 = Template(
        rs)  # Create second template. This is for the main pages.
    # Show grid columns and margins if rootStyle.showGrid or rootStyle.showGridColumns are True
    template2.grid(rs)
    # Show baseline grid if rs.showBaselineGrid is True
    template2.baselineGrid(rs)
    template2.cContainer(4, 0, 2, 3, rs)  # Empty image element, cx, cy, cw, ch
    template2.cContainer(0, 5, 2, 3, rs)
    template2.cContainer(2, 2, 2, 2, rs)
    template2.cContainer(2, 0, 2, 2, rs)
    template2.cContainer(4, 6, 2, 2, rs)
    template2.cTextBox(FS,
                       0,
                       0,
                       2,
                       5,
                       rs,
                       flowId1,
                       nextBox=flowId2,
                       nextPage=0,
                       fill=BOX_COLOR)
    template2.cTextBox(FS,
                       2,
                       4,
                       2,
                       4,
                       rs,
                       flowId2,
                       nextBox=flowId3,
                       nextPage=0,
                       fill=BOX_COLOR)
    template2.cTextBox(FS,
                       4,
                       3,
                       2,
                       3,
                       rs,
                       flowId3,
                       nextBox=flowId1,
                       nextPage=1,
                       fill=BOX_COLOR)
    # Create page number box. Pattern pageNumberMarker is replaced by actual page number.
    template2.cText(FS + rs['pageIdMarker'],
                    6,
                    0,
                    style=rs,
                    font=BOOK,
                    fontSize=12,
                    fill=BOX_COLOR)

    # Create new document with (w,h) and fixed amount of pages.
    # Make number of pages with default document size.
    # Initially make all pages default with template2
    doc = Document(rs, autoPages=3, template=template2)

    # Cache some values from the root style that we need multiple time to create the tag styles.
    fontSize = rs['fontSize']
    leading = rs['leading']
    rLeading = rs['rLeading']
    listIndent = rs['listIndent']
    language = rs['language']

    # Add styles for whole document and text flows.
    # Note that some values are defined here for clarity, even if their default root values
    # are the same.
    doc.newStyle(name='chapter', font=BOOK)
    doc.newStyle(name='title', fontSize=3 * fontSize, font=BOLD)
    doc.newStyle(name='subtitle', fontSize=2.6 * fontSize, font=BOOK_ITALIC)
    doc.newStyle(name='author',
                 fontSize=2 * fontSize,
                 font=BOOK,
                 fill=(1, 0, 0))
    doc.newStyle(name='h1',
                 fontSize=2 * fontSize,
                 font=BLACK,
                 fill=(1, 0, 0),
                 leading=2.5 * leading,
                 tracking=H1_TRACK,
                 postfix='\n')
    doc.newStyle(name='h2',
                 fontSize=5 * fontSize,
                 font=LIGHT_CONDENSED,
                 fill=0,
                 leading=1 * leading,
                 rLeading=0,
                 tracking=H2_TRACK,
                 prefix='',
                 postfix='\n')
    doc.newStyle(name='h3',
                 fontSize=1.1 * fontSize,
                 font=MEDIUM,
                 fill=0,
                 leading=leading,
                 rLeading=0,
                 rNeedsBelow=2 * rLeading,
                 tracking=H3_TRACK,
                 prefix='',
                 postfix='\n')
    doc.newStyle(name='h4',
                 fontSize=1.1 * fontSize,
                 font=BOOK,
                 fill=0,
                 leading=leading,
                 rLeading=0,
                 rNeedsBelow=2 * rLeading,
                 tracking=H3_TRACK,
                 paragraphTopSpacing=U,
                 paragraphBottomSpacing=U,
                 prefix='',
                 postfix='\n')

    # Spaced paragraphs.
    doc.newStyle(name='p',
                 fontSize=fontSize,
                 font=BOOK,
                 fill=0.1,
                 prefix='',
                 postfix='\n',
                 rTracking=P_TRACK,
                 leading=14,
                 rLeading=0,
                 align=LEFT_ALIGN,
                 hyphenation=True)
    doc.newStyle(name='b', font=SEMIBOLD)
    doc.newStyle(name='em', font=BOOK_ITALIC)
    doc.newStyle(name='hr', stroke=(1, 0, 0), strokeWidth=4)
    doc.newStyle(name='br',
                 postfix='\n')  # Simplest way to make <br/> show newline
    doc.newStyle(name='a', prefix='', postfix='')
    doc.newStyle(name='img',
                 leading=leading,
                 fontSize=fontSize,
                 font=BOOK,
                 stroke=1,
                 fill=None)

    # Footnote reference index.
    doc.newStyle(name='sup',
                 font=MEDIUM,
                 rBaselineShift=0.6,
                 prefix='',
                 postfix=' ',
                 fontSize=0.6 * fontSize)
    doc.newStyle(
        name='li',
        fontSize=fontSize,
        font=BOOK,
        tracking=P_TRACK,
        leading=leading,
        hyphenation=True,
        # Lists need to copy the listIndex over to the regalar style value.
        tabs=[(listIndent, LEFT_ALIGN)],
        indent=listIndent,
        firstLineIndent=1,
        postfix='\n')
    doc.newStyle(name='ul', prefix='', postfix='')
    doc.newStyle(name='literatureref',
                 fill=0.5,
                 rBaselineShift=0.2,
                 fontSize=0.8 * fontSize)
    doc.newStyle(name='footnote', fill=(1, 0, 0), fontSize=0.8 * U, font=BOOK)
    doc.newStyle(name='caption',
                 tracking=P_TRACK,
                 language=language,
                 fill=0.2,
                 leading=leading * 0.8,
                 fontSize=0.8 * fontSize,
                 font=BOOK_ITALIC,
                 indent=U / 2,
                 tailIndent=-U / 2,
                 hyphenation=True)

    # Change template of page 1
    page1 = doc[1]
    page1.setTemplate(template1)

    # Create main Galley for this page, for pasting the sequence of elements.
    galley = Galley()
    t = Typesetter(doc, galley)
    t.typesetFile(MD_PATH)

    # Fill the main flow of text boxes with the ML-->XHTML formatted text.
    c = Composer(doc)
    c.compose(galley, page1, flowId1)

    return doc
示例#14
0
def makeDocument():
    u"""Demo page composer."""
    tt = time() # Keep track of time, in case SHOW_TIMER is True

    # Set some values of the default template (as already generated by the document).
    # Make squential unique names for the flow boxes inside the templates
    flowId0 = MAIN_FLOW+'0' 
    flowId1 = MAIN_FLOW+'1'
    flowId2 = MAIN_FLOW+'2'
        
    # Template 1
    template1 = Template(rs) # Create template of main size. Front page only.
    # Show grid columns and margins if rootStyle.showGrid or rootStyle.showGridColumns are True
    template1.grid(rs) 
    # Show baseline grid if rs.showBaselineGrid is True
    template1.baselineGrid(rs)
    # Create empty image place holders. To be filled by running content on the page.
    template1.cContainer(4, 0, 2, 4, rs)  # Empty image element, cx, cy, cw, ch
    template1.cContainer(0, 5, 2, 3, rs)
    # Create linked text boxes. Note the "nextPage" to keep on the same page or to next.
    template1.cTextBox('', 0, 0, 2, 5, rs, flowId0, nextBox=flowId1, nextPage=0, fill=BOX_COLOR)
    template1.cTextBox('', 2, 0, 2, 8, rs, flowId1, nextBox=flowId2, nextPage=0, fill=BOX_COLOR)
    template1.cTextBox('', 4, 4, 2, 4, rs, flowId2, nextBox=flowId0, nextPage=1, fill=BOX_COLOR)
    # Create page number box. Pattern pageNumberMarker is replaced by actual page number.
    template1.cText(rs['pageNumberMarker'], 6, 0, rs, font=BOOK, fontSize=12, fill=BOX_COLOR)

    # Template 2
    template2 = Template(rs) # Create second template. This is for the main pages.
    # Show grid columns and margins if rootStyle.showGrid or rootStyle.showGridColumns are True
    template2.grid(rs) 
    # Show baseline grid if rs.showBaselineGrid is True
    template2.baselineGrid(rs)
    template2.cContainer(4, 0, 2, 3, style=rs)  # Empty image element, cx, cy, cw, ch
    template2.cContainer(0, 5, 2, 3, style=rs)
    template2.cContainer(2, 2, 2, 2, style=rs)
    template2.cContainer(2, 0, 2, 2, style=rs)
    template2.cContainer(4, 6, 2, 2, style=rs)
    template2.cTextBox('', 0, 0, 2, 5, style=rs, flowId0, nextBox=flowId1, nextPage=0, fill=BOX_COLOR)
    template2.cTextBox('', 2, 4, 2, 4, style=rs, flowId1, nextBox=flowId2, nextPage=0, fill=BOX_COLOR)
    template2.cTextBox('', 4, 3, 2, 3, style=rs, flowId2, nextBox=flowId0, nextPage=1, fill=BOX_COLOR)
    # Create page number box. Pattern pageNumberMarker is replaced by actual page number.
    template2.cText(rs['pageNumberMarker'], 6, 0, style=rs, font=BOOK, fontSize=12, fill=BOX_COLOR)
   
    # Create new document with (w,h) and fixed amount of pages.
    # Make number of pages with default document size.
    # Initially make all pages default with template2
    doc = Document(rs, autoPages=2, template=template2) 
 
    # Cache some values from the root style that we need multiple time to create the tag styles.
    fontSize = rs['fontSize']
    leading = rs['leading']
    rLeading = rs['rLeading']
    listIndent = rs['listIndent']
    language = rs['language']
    
    # Add styles for whole document and text flows.  
    # Note that some values are defined here for clarity, even if their default root values
    # are the same.             
    doc.newStyle(name='chapter', font=BOOK)    
    doc.newStyle(name='title', fontSize=3*fontSize, font=BOLD)
    doc.newStyle(name='subtitle', fontSize=2*fontSize, font=BOOK_ITALIC)
    doc.newStyle(name='author', fontSize=2*fontSize, font=BOOK, fill=(1, 0, 0))
    doc.newStyle(name='h1', fontSize=fontSize, font=SEMIBOLD, fill=(1, 0, 0),
        leading=2*fontSize, tracking=H1_TRACK, postfix='\n')
    doc.newStyle(name='h2', fontSize=fontSize, font=SEMIBOLD, fill=(0, 0.5, 1),
        leading=1*fontSize, rLeading=0, tracking=H2_TRACK, postfix='\n')
    doc.newStyle(name='h3', fontSize=fontSize, font=MEDIUM, fill=0, 
        leading=1*fontSize, rLeading=0, rNeedsBelow=2*rLeading, tracking=H3_TRACK,
        postfix='\n')
    
    # Spaced paragraphs.
    doc.newStyle(name='p', fontSize=fontSize, font=BOOK, fill=0.1, prefix='', postfix='\n',
        rTracking=P_TRACK, leading=14, rLeading=0, align=LEFT, hyphenation=True)
    doc.newStyle(name='b', font=SEMIBOLD)
    doc.newStyle(name='em', font=BOOK_ITALIC)
    doc.newStyle(name='hr', stroke=(1, 0, 0), strokeWidth=4)
    doc.newStyle(name='br', postfix='\n') # Simplest way to make <br/> be newline
    doc.newStyle(name='img', leading=leading, fontSize=fontSize, font=BOOK,)
    
    # Footnote reference index.
    doc.newStyle(name='sup', font=MEDIUM, rBaselineShift=0.6,
        fontSize=0.65*fontSize)
    doc.newStyle(name='li', fontSize=fontSize, font=BOOK, 
        tracking=P_TRACK, leading=leading, hyphenation=True, 
        # Lists need to copy the listIndex over to the regalar style value.
        tabs=[(listIndent, LEFT)], indent=listIndent, 
        firstLineIndent=1, postfix='\n')
    doc.newStyle(name='ul',)
    doc.newStyle(name='literatureref', fill=0.5, rBaselineShift=0.2, fontSize=0.8*fontSize)
    doc.newStyle(name='footnote', fill=(1, 0, 0), fontSize=0.8*U, font=BOOK)
    doc.newStyle(name='caption', tracking=P_TRACK, language=language, fill=0.2, 
        leading=leading*0.8, fontSize=0.8*fontSize, font=BOOK_ITALIC, 
        indent=U/2, tailIndent=-U/2, hyphenation=True)

    if SHOW_TIMER:
        print 'Time styles %0.3f' % (time()-tt)
        tt = time()
    
    # Change template of page 1
    page0 = doc[0]
    page0.setTemplate(template1)
    
    ttt = ''
    for n in range(100):
        ttt += 'abcdefg%d\n' % n
    ttt = newFS(ttt, rs)
    ttt = page0.textBox(ttt, point(rs.get('pl'), rs.get('pt')), w=11*14, h=50*14, fill=(0.8, 0.8, 0.8, 0.5))
    page0.textBox(ttt, point=(rs.get('pl')+11*14+14, rs.get('pt')), w=11*14, h=50*14, fill=(0.8, 0.8, 0.8, 0.5))
    
    if SHOW_TIMER:
        print 'Time template %0.3f' % (time()-tt)
        tt = time()
    
    # Create main Galley for this page, for pasting the sequence of elements.    
    g = Galley() 
    t = Typesetter(doc, g)
    t.typesetFile(MD_PATH)
    
    if SHOW_TIMER:
        print 'Time typesetter %0.3f' % (time()-tt)
        tt = time()
    
    # Fill the main flow of text boxes with the ML-->XHTML formatted text. 
    c = Composer(doc)
    c.compose(g, doc[0], flowId0)
    
    if SHOW_TIMER:
        print 'Time compose %0.3f' % (time()-tt)
    
    return doc
示例#15
0
from pagebot.toolbox.color import color, blackColor
from pagebot.constants import A4

W, H = A4

MARKDOWN_PATH = 'EmbeddedPython.md'

context = getContext()

doc = Document(originTop=False, w=W, h=H, autoPages=1)
#print(doc.styles.keys())
doc.addStyle('h1', dict(textFill=blackColor), force=True)
doc.addStyle('h2', dict(textFill=blackColor), force=True)
doc.addStyle('p', dict(textFill=blackColor), force=True)

ts = Typesetter(context, doc.styles, g)
ts.typesetFile(MARKDOWN_PATH)

page = doc[1]  # Get the first/single page of the document.
page.padding = 40  # TODO: order if 4 values?

# Make rect as page element centered with centered origin.
conditions = [Fit()]
g = newTextBox(parent=page,
               conditions=conditions,
               textFill=blackColor,
               autoPages=10)

# Solve the layout conditions of the red rectangle.
# Show if one of the conditions failed to solve.
score = page.solve()
示例#16
0
view.showFrame = True
#view.showDimensions = True

if 0:
    for pn, pages in doc.pages.items():
        page = pages[0]
        for artboard in page.elements:
            page.gridX = artboard.gridX
            page.gridY = artboard.gridY
            print(artboard.xy, artboard.size)
            for e in artboard.elements:
                print(e)
                for e1 in e.elements:
                    print('\t', e)
            #print('=====', artboard.gridX, artboard.gridY)

# Compile text content
if 0:
    t = Typesetter(doc.context)
    galley = t.typesetFile(textPath)

    # Anchor the text in the first text column
    page = doc[1]
    #print(page.deepFind('Article1'))
    targets = dict(doc=doc, page=page)
    composer = Composer(doc)
    composer.compose(galley, targets=targets)

EXPORT_PATH = '_export/TestImage.pdf'
doc.export(EXPORT_PATH)
示例#17
0
def makeDocument():
    u"""Demo page composer by templates."""

    # Set some values of the default template (as already generated by the document).
    # Make squential unique names for the flow boxes inside the templates
    flowId1 = MAIN_FLOW + '1'
    flowId2 = MAIN_FLOW + '2'
    flowId3 = MAIN_FLOW + '3'

    # Template 1
    template1 = Template()  # Create template of main size. Front page only.
    # Create empty image place holders. To be filled by running content on the page.
    newColRect(4, 0, 2, 4,
               parent=template1)  # Empty image element, cx, cy, cw, ch
    newColRect(0, 5, 2, 3, parent=template1)
    # Create linked text boxes. Note the "nextPage" to keep on the same page or to next.
    newColTextBox('',
                  0,
                  0,
                  2,
                  5,
                  parent=template1,
                  name=flowId1,
                  nextElement=flowId2,
                  nextPage=0,
                  fill=BOX_COLOR)
    newColTextBox('',
                  2,
                  0,
                  2,
                  8,
                  parent=template1,
                  name=flowId2,
                  nextElement=flowId3,
                  nextPage=0,
                  fill=BOX_COLOR)
    newColTextBox('',
                  4,
                  4,
                  2,
                  4,
                  parent=template1,
                  name=flowId3,
                  nextElement=flowId1,
                  nextPage=1,
                  fill=BOX_COLOR)
    # Create page number box. Pattern pageNumberMarker is replaced by actual page number.
    pnString = context.newString('%d',
                                 style=dict(font=BOOK,
                                            fontSize=12,
                                            fill=BOX_COLOR))
    newColText(pnString, 6, 0, parent=template1)
    """
    # Template 2
    template2 = Template(style=rs) # Create second template. This is for the main pages.
    template2.cContainer(4, 0, 2, 3, rs)  # Empty image element, cx, cy, cw, ch
    template2.cContainer(0, 5, 2, 3, rs)
    template2.cContainer(2, 2, 2, 2, rs)
    template2.cContainer(2, 0, 2, 2, rs)
    template2.cContainer(4, 6, 2, 2, rs)
    template2.cTextBox(FS, 0, 0, 2, 5, rs, flowId1, nextBox=flowId2, nextPage=0, fill=BOX_COLOR)
    template2.cTextBox(FS, 2, 4, 2, 4, rs, flowId2, nextBox=flowId3, nextPage=0, fill=BOX_COLOR)
    template2.cTextBox(FS, 4, 3, 2, 3, rs, flowId3, nextBox=flowId1, nextPage=1, fill=BOX_COLOR)
    # Create page number box. Pattern pageNumberMarker is replaced by actual page number.
    template2.cText(FS+rs['pageIdMarker'], 6, 0, style=rs, font=BOOK, fontSize=12, fill=BOX_COLOR)
    """
    # Create new document with (w,h) and fixed amount of pages.
    # Make number of pages with default document size.
    # Initially make all pages default with template2
    doc = Document(rs, autoPages=1, language=LANGUAGE, template=template1)

    # Add styles for whole document and text flows.
    # Note that some values are defined here for clarity, even if their default root values
    # are the same.
    doc.newStyle(name='chapter', font=BOOK)
    doc.newStyle(name='title', fontSize=3 * fontSize, font=BOLD)
    doc.newStyle(name='subtitle', fontSize=2.6 * fontSize, font=BOOK_ITALIC)
    doc.newStyle(name='author',
                 fontSize=2 * fontSize,
                 font=BOOK,
                 textFill=(1, 0, 0))
    doc.newStyle(name='h1',
                 fontSize=2.6 * fontSize,
                 font=SEMIBOLD_CONDENSED,
                 textFill=0.2,
                 leading=2.6 * fontSize,
                 tracking=H1_TRACK,
                 prefix='\n',
                 postfix='\n',
                 paragraphTopSpacing=U,
                 paragraphBottomSpacing=U)
    doc.newStyle(name='h2',
                 fontSize=2 * fontSize,
                 font=LIGHT_CONDENSED,
                 textFill=(1, 0, 0),
                 leading=2.2 * leading,
                 rLeading=0,
                 tracking=H2_TRACK,
                 prefix='',
                 postfix='\n')
    doc.newStyle(name='h3',
                 fontSize=1.1 * fontSize,
                 font=MEDIUM,
                 textFill=0,
                 leading=1.4 * fontSize,
                 rLeading=0,
                 rNeedsBelow=2 * rLeading,
                 tracking=H3_TRACK,
                 prefix='',
                 postfix='\n')
    # paragraphTopSpacing=U, paragraphBottomSpacing=U only work if there is a prefix/postfix
    doc.newStyle(name='h4',
                 fontSize=1.1 * fontSize,
                 font=BOOK,
                 textFill=0,
                 leading=leading,
                 rLeading=0,
                 rNeedsBelow=2 * rLeading,
                 tracking=H3_TRACK,
                 paragraphTopSpacing=U,
                 paragraphBottomSpacing=U,
                 prefix='\n',
                 postfix='\n')

    # Spaced paragraphs.
    doc.newStyle(name='p',
                 fontSize=fontSize,
                 font=BOOK,
                 textFill=0.1,
                 prefix='',
                 postfix='\n',
                 rTracking=P_TRACK,
                 leading=14,
                 rLeading=0,
                 xTextAlign=LEFT,
                 hyphenation=True)
    doc.newStyle(name='b', font=SEMIBOLD)
    doc.newStyle(name='em', font=BOOK_ITALIC)
    doc.newStyle(name='hr', stroke=(1, 0, 0), strokeWidth=4)
    doc.newStyle(name='br',
                 postfix='\n')  # Simplest way to make <br/> show newline
    doc.newStyle(name='a', prefix='', postfix='')
    doc.newStyle(name='img',
                 leading=leading,
                 fontSize=fontSize,
                 font=BOOK,
                 stroke=1,
                 fill=None)

    # Footnote reference index.
    doc.newStyle(name='sup',
                 font=MEDIUM,
                 rBaselineShift=0.6,
                 prefix='',
                 postfix=' ',
                 fontSize=0.6 * fontSize)
    doc.newStyle(
        name='li',
        fontSize=fontSize,
        font=BOOK,
        tracking=P_TRACK,
        leading=leading,
        hyphenation=True,
        # Lists need to copy the listIndex over to the regalar style value.
        tabs=[(listIndent, LEFT)],
        indent=listIndent,
        firstLineIndent=1,
        prefix='',
        postfix='\n'),
    doc.newStyle(name='ul', prefix='', postfix='')
    doc.newStyle(name='literatureref',
                 fill=0.5,
                 rBaselineShift=0.2,
                 fontSize=0.8 * fontSize)
    doc.newStyle(name='footnote', fill=(1, 0, 0), fontSize=0.8 * U, font=BOOK)
    doc.newStyle(name='caption',
                 tracking=P_TRACK,
                 language=language,
                 fill=0.2,
                 leading=leading * 0.8,
                 fontSize=0.8 * fontSize,
                 font=BOOK_ITALIC,
                 tailIndent=-U / 2,
                 hyphenation=True)

    # Change template of page 1
    page1 = doc[0]
    page1.template = template1

    # Create main Galley for this page, for pasting the sequence of elements.
    galley = Galley()
    t = Typesetter(doc, galley)
    t.typesetFile(MD_PATH)

    # Fill the main flow of text boxes with the ML-->XHTML formatted text.
    c = Composer(makeNewPage=True)
    c.compose(galley, page1, flowId1)

    return doc
示例#18
0
def makeSite(styles, viewId):
    site = Site(styles=styles)
    doc = site.newDocument(viewId=viewId, autoPages=1, defaultImageWidth=MAX_IMAGE_WIDTH)
    
    doc.theme = theme

    view = doc.view
    view.resourcePaths = ('css','fonts','images','js')
    view.jsUrls = (
        URL_JQUERY, 
        'js/jquery.bbslider.min.js',
        #URL_MEDIA, 
        #'js/sitemain.js', 
    )
    
    # Generate css by mapping theme.mood on cssPy 
    cssPath = 'css/nanostyle_py.css'
    doc.context.b.writeCss(cssPath, cssPy % theme.mood)

    view.cssUrls = (
        'css/jquery.bbslider.css',
        'fonts/webfonts.css', 
        'css/normalized.css', 
        cssPath,
    )
    BASE_FONT_SIZE = 16
    view.jsCode = """
    function setBaseFontSize(){
        /*document.getElementsByTagName('body')[0].style['font-size'] = %d * window.devicePixelRatio + 'px';*/
    }
    window.onload = setBaseFontSize;
    """ % BASE_FONT_SIZE

    # Make the all pages and elements of the site as empty containers, that then can
    # be selected and filled by the composer, using the galley content.
    # Of the MarkDown text can decide to create new elements inside selected elements.
    template = makeTemplate(doc)    

    page = doc[1]
    page.applyTemplate(template) # Copy element tree to page.

    # By default, the typesetter produces a single Galley with content and code blocks.    
    t = Typesetter(doc.context)
    galley = t.typesetFile(MD_PATH)
    
    # Create a Composer for this document, then create pages and fill content. 
    composer = Composer(doc)

    # The composer executes the embedded Python code blocks that indicate where content should go.
    # by the HtmlContext. Feedback by the code blocks is added to verbose and errors list
    targets = dict(doc=doc, page=page, template=template)
    composer.compose(galley, targets=targets)

    if VERBOSE:
        if targets['verbose']:
            print('Verbose\n', '\n'.join(targets['verbose']))
        # In case there are any errors, show them.
        if targets['errors']:
            print('Errors\n', '\n'.join(targets['errors']))
    
    # Find the navigation elements and fill them, now we know all the pages.
    makeNavigation(doc)

    # https://www.hyphenator.net/en/word/...
    unknownWords = doc.spellCheck(LANGUAGE_EN)
    if unknownWords:
        print(unknownWords)

    return doc
示例#19
0
import os
import pagebot
from pagebot.typesetter import Typesetter
from pagebot.elements import *
from pagebot.document import Document

doc = Document()
g = Galley()
ts = Typesetter(doc, g)

ROOT_PATH = pagebot.getRootPath()
MD_PATH = ROOT_PATH + "/Examples/Howto/TOC.md"

ts.typesetFile(MD_PATH)
for e in g.elements:
    #print e.fs
    pass
    #print e

示例#20
0
from pagebot.typesetter import Typesetter

# Path to markdown file, including Python code blocks.
MARKDOWN_PATH = u"TEST_CONTENT.md"

# Export PDF, showing what is found inside the markdown file.
EXPORT_PATH = '_export/EmbeddedPythonCodeBlocks.pdf'
# Create an unbound Typesetter instance (trying to find a Document 
# instance in the codeblock result. If no Galley instance is supplied
# to the Typesetter, it will create one.
t = Typesetter()
# Parse the markdown content and execute the embedded Python code blocks.
t.typesetFile(MARKDOWN_PATH)
# Typesetter found document definition inside content.
print 'Document title:', t.doc.title 
# Multiple code blocks found with identical identifier.
# Added counter 'Views_0' to 'Views' to make it unique. 
print 'Found code blocks:', t.codeBlocks.keys()

t.doc.export(EXPORT_PATH)
示例#21
0
def makeDocument():
    """Re-generate the original Type3-PeopleInType chapter as PDF output."""

    context = DrawBotContext()

    # Create new document with (w,h) and fixed amount of pages.
    # Make number of pages with default document size.
    # Initially make all pages default with template
    # One page, just the cover.
    doc = Document(w=W,
                   h=H,
                   title='Type Magazine #3',
                   autoPages=endPage - startPage + 1,
                   baselineGrid=BASELINE,
                   baselineStart=BASELINE_START,
                   style=styles,
                   templates=getTemplates(),
                   startPage=startPage,
                   originTop=False,
                   context=context)

    # Get the current view of the document. This allows setting of
    # parameters how the document is represented on output.
    view = doc.view
    view.w, view.h = W, H
    # Set view options. Full list is in elements/views/baseviews.py
    view.padding = 40  # Showing cropmarks and registration marks
    # need >= 20 padding of the view.
    view.showRegistrationMarks = True
    view.showCropMarks = True
    view.showFrame = True
    view.showPadding = True
    view.showNameInfo = True
    view.showMetaInfo = False
    view.showTextOverflowMarker = True
    view.showOrigin = False  # Show origin marker
    view.showElementOrigin = False  # Don't show the origin of other elements.

    view.showGrid = [GRID_COL, GRID_ROW]
    view.showBaselines = True

    view.showSpreadPages = True
    view.showSpreadMiddleAsGap = False

    # PageBot article
    _, backgroundHeight = context.imageSize(BACKGROUND_PDF)
    backgroundIndex = 0
    for pn in range(startPage, endPage + 1):
        page = doc[pn]
        setPageStyle(page, backgroundIndex)
        backgroundIndex += 1

    if 1:
        page = doc[startPage + 2]
        print(page)
        t = Typesetter(context, styles=styles, imageAsElement=True)
        galley = t.typesetFile(CONTENT_PATH, e=page)
        composer = Composer(doc)
        targets = dict(composer=composer,
                       doc=doc,
                       page=page,
                       style=doc.styles,
                       box=page.select('people'),
                       newTextBox=newTextBox)

        composer.compose(galley, targets=targets, page=page)

    date = now()
    if EXPORT_PDF:  # Export as PDF
        exportPath = EXPORT_PATH_PDF % (date.year, date.month, date.day,
                                        date.hour, startPage, endPage)
        doc.export(exportPath)
    if EXPORT_PNG:  # Export as PNG without cropmarks for mapping purpose
        doc.view.padding = 0
        exportPath = EXPORT_PATH_PNG % (startPage, endPage)
        doc.export(exportPath)