Editorial Workflows

PDF (Docverter)

unlisted workflow

Install Workflow...

This workflow contains at least one Python script. Only use it if you trust the person who shared this with you, and if you know exactly what it does.

I understand, install the workflow!

This is a workflow for Editorial, a Markdown and plain text editor for iOS. To download it, you need to view this page on a device that has the app installed.

Description: Warning: this has some problems and does not convert well. See my comments in the first action in the workflow.

Convert the markdown file open in Editorial to html, add a CSS and convert to PDF using Docverter, an online service.

Comments: Comment Feed (RSS)

There are no comments yet.

+ Add Comment

Workflow Preview
About this workflow ?
Source Code
#coding: utf-8

"""
Convert the current markdown file to html, add a CSS and send to the online service Docverter to convert to PDF. Displays the PDF in Editorial, whence you can open-in another app, email or print it (you don't need to use dropbox). The CSS is for printing, with classes .floatright (usually for an image) and .pagebreak.

Requires you to be online.

The Python script to interract with Docverter is by, Caleb McDaniel, see here:
http://wcm1.web.rice.edu/pandoc-on-ios.html

Docverter features:
- Use @page CSS features, page size, margins, headers and footers.

- Links in the pdf work.

- There are only a few fonts available; you can use @fontface in the CSS to specify more, but I haven't tried this.

- I convert the markdown to html and add the CSS and send that to Docverter rather than send the markdown and CSS separately, because this seemed more reliable, and i don't like Docverter's markdown table syntax.

____

Using the CSS in this workflow:
	
Set page size, margins, header and footer in the CSS @page. 
____

Images: 1 px is 0.26 mm (the dpi doesn't matter):
- An image 600 px wide is about 160 mm wide, the width of the print area of typical PDF. If an image is wider than about 600 px, then the CSS max-width:100% rule will reduce the image to fit the print area.
- An image about 20 px high is about 5 mm high, suitable for inserting inline with text in a block.
____

Class .floatright: for one block element, usually an image. You can't apply it to a <div> element around several Markdown elements, because the enclosed markdown is not converted to html. To use:
	
![](img link){: .floatright }
____

Class .pagebreak: inserts a page break before the element. To use:
    
This is a block element.
{: .pagebreak }

A setext style header {: .pagebreak }
=================================

### A hash style header {: .pagebreak }

or:
[blank line]
<div class=pagebreak></div>
[blank line]

"""
Document Text ?
Folded Text
  • Include
  • Replace with:
Convert markdown to html, with tables & attribute lists ?
Source Code
#coding: utf-8
import markdown
import workflow

text = workflow.get_input()
text = markdown.markdown (text, extensions=['tables', 'attr_list'] )
workflow.set_output(text)
Set Variable ?
Variable Name
Body
Value
Input
Get Current File Name ?
Include Folder
OFF
Include Extension
OFF
Set Variable ?
Variable Name
FileName
Value
Input
Get the CSS ?
Source Code
#coding: utf-8
# basic CSS, for a Docverter PDF, Peter Hopcroft, jan 2014

import workflow

action_out = """

div.footer {display:block; position:running(footer);}

@page {size: A4;
      margin-left: 30mm; margin-right: 30mm;
      margin-top: 25mm; margin-bottom: 30mm;
      padding-left: 0mm; padding-right: 0mm;
      padding-top: 0mm; padding-bottom: 2mm;
      border-bottom-style: solid; border-bottom-width: 0.5px; 
      border-bottom-color: grey; 
      @bottom-left{content: element(footer); vertical-align: top;
      		margin-top: 0mm; padding-top: 2mm;};
      @bottom-right{content: counter(page); vertical-align: top;
      		margin-top: 0mm; padding-top: 5mm;};
      /* !! need to set padding-top different so text and number align */
      }
      
*			{padding: 0mm; margin: 0mm; margin-top: 2.5mm;
    	font-size: 13pt; font-family: serif; 
     	line-height: 130%;
			vertical-align: baseline;}

h1, h2, h3 {page-break-after: avoid;}

h1		{font-size: 16pt; font-weight: bold;
			margin-top: 14mm; margin-bottom: 4mm}

h2		{font-size: 13pt; font-weight: bold;
 	   margin-top: 8mm; margin-bottom: 0mm;}

h3, h4, h5, h6
			{font-size: 13pt; font-weight: normal;
  	  margin-top: 8mm; margin-bottom: 0mm;
			font-style: italic;}

em		{font-style: italic;}

strong	{font-weight: bold;}

blockquote {margin-left: 5.5mm; font-size: 12pt;}	/* match list indent */

pre		{font-size: 11pt; padding-left: 5.5mm;	/* match list indent */
			font-family: 'courier', monospace;}

img		{vertical-align: baseline;}
img		{max-width: 100%;} /* !! does not work */

hr		{margin-top: 3mm; margin-bottom:3.8mm;
			text-align: center; width: 30%; color: grey; height: thin;}

ul		{list-style-type: square; margin-left: 5mm;}
ol		{list-style-type: decimal; margin-left: 5.5mm;}

table	{border-top-style: solid; border-top-width: 0.5px; 
      border-top-color: grey;
      border-bottom-style: solid; border-bottom-width: 0.5px; 
      border-bottom-color: grey;
			border-collapse: collapse;
			margin-top: 3.3mm; margin-bottom: 4mm;}

th,td	{padding-right: 4mm; padding-bottom: 2.5mm; text-align: left;}
th		{padding-top: 3.3mm; vertical-align: top; font-weight: bold;}
td		{padding-top: 0mm; vertical-align: top;}

/* classes */

.floatright	{float:right; width:50%;  /* !! vertical alignment not right */
    margin-left: 0mm; margin-right: 0mm; 
    margin-top: 0mm; margin-bottom: 0mm; 
		padding-left: 4mm; padding-right: 0mm; 
    padding-top: 0mm; padding-bottom: 3mm;}

.pagebreak {page-break-before: always;}

"""

workflow.set_output(action_out)
Set Variable ?
Variable Name
CSS
Value
Input
Create the full html ?
Text
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>FileName</title> <style type="text/css"> CSS </style> </head> <body> Body </body> </html>
Use Docverter to convert to PDF; preview PDF; can share ?
Source Code
#! /usr/bin/env python
#coding: utf-8
 
## based on iMDtoPDF.py by Caleb McDaniel
## see http://wcm1.web.rice.edu/pandoc-on-ios.html
 
## This is a wrapper script for sending documents to Docverter
## for conversion from markdown to PDF using Pandoc. Typically
## Docverter calls are made with cURL; this script uses httplib.
## It is intended for use with Pythonista on iOS, so output file
## is uploaded to Dropbox after document conversion.
## For more information, see: http://www.docverter.com/api.html
 
import clipboard
import datetime
import httplib
import mimetypes
import workflow
import os
import console
import codecs
 
## Helper functions for posting multipart/form-data request
## using standard libraries. Updated to reflect changes to
## httplib in Python 2.0.
## {{{ http://code.activestate.com/recipes/146306/ (r1)
 
def post_multipart(host, selector, fields, files):
    """
    Post fields and files to an http host as multipart/form-data.
    fields is a sequence of (name, value) elements for regular form fields.
    files is a sequence of (name, filename, value) elements for data to be uploaded as files
    Return the server's response page.
    """
    content_type, body = encode_multipart_formdata(fields, files)
    h = httplib.HTTPConnection(host)
    h.putrequest('POST', selector)
    h.putheader('content-type', content_type)
    h.putheader('content-length', str(len(body)))
    h.endheaders()
    h.send(body.encode('utf-8', 'replace'))
#   h.send(body)
    response = h.getresponse()
    output = response.read()
    return output
    # return h.file.read()
 
def encode_multipart_formdata(fields, files):
    """
    fields is a sequence of (name, value) elements for regular form fields.
    files is a sequence of (name, filename, value) elements for data to be uploaded as files
    Return (content_type, body) ready for httplib.HTTP instance
    """
    BOUNDARY = '----------ThIs_Is_tHe_bouNdaRY_$'
    CRLF = '\r\n'
    L = []
    for (key, value) in fields:
        L.append('--' + BOUNDARY)
        L.append('Content-Disposition: form-data; name="%s"' % key)
        L.append('')
        L.append(value)
    for (key, filename, value) in files:
        L.append('--' + BOUNDARY)
        L.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename))
        L.append('Content-Type: %s' % get_content_type(filename))
        L.append('')
        L.append(value)
    L.append('--' + BOUNDARY + '--')
    L.append('')
    body = CRLF.join(L)
    content_type = 'multipart/form-data; boundary=%s' % BOUNDARY
    return content_type, body
 
def get_content_type(filename):
    return mimetypes.guess_type(filename)[0] or 'application/octet-stream'
 
# end of http://code.activestate.com/recipes/146306/ }}}
 
# Now let's DO this

# get workflow variables
Text = workflow.get_input()
FileName = workflow.get_variable('FileName')

# set file names
html_file_name = FileName + '.html'
pdf_file_name = FileName + '.pdf'

# Put the html in a file to send to Docverter.

f = codecs.open(html_file_name, "w", encoding='utf-8')
f.write(Text)
 
# Set Docverter options and define fields using lists.
# Other options available at http://www.docverter.com/api.html#toc_2
fields = [("from", "html"), ("to", "pdf")]
files = [("input_files[]", html_file_name, codecs.open(html_file_name, "r", encoding='utf-8').read())]
 
pdf = post_multipart("c.docverter.com", "/convert", fields, files)
o = open(pdf_file_name, "w").write(pdf)

# open PDF file in Editorial (can then share)
pdf_file_path = os.path.abspath(pdf_file_name)
console.quicklook(pdf_file_path)

# delete temporary files
os.remove(html_file_name)
os.remove(pdf_file_name)
Stop ?
Stop
  • This Workflow
  • Repeat Block
Show HUD Alert
ON
Message
Done
Get markdown text - temporary action - remove soon ?
Source Code
#coding: utf-8
# example markdown text for docverter, with footer, page breaks
import workflow

html = """

<div class="footer">Example markdown</div>

# Sampler
Typical Markdown text, for developing  a style sheet. Has examples of all markdown syntax and has the look of a real document. Requires CSS classes *floatright* and *pagebreak*. I use h1, h2, h3 headings. Peter Hopcroft, January 2014.

## Examples of links
Most of this document has the basic syntax of [Python markdown](http://pythonhosted.org/Markdown/index.html) without extensions (virtually the same as [John Gruber's original markdown](http://daringfireball.net/projects/markdown/)).  At the end are the extensions I use; if you use other extensions, add examples at the end.

The text comes from the out-of-copyright book: 'The American Practical Brewer and Tanner', 1815, by Joseph Coppinger. I got it from a [Gutenberg EBook](http://www.gutenberg.org/ebooks/20663) and I am reusing it under the terms of the [their license](http://www.gutenberg.org/wiki/Gutenberg:The_Project_Gutenberg_License).

>To offer an apology for giving these subjects a place in this publication, seem wholly unnecessary, when their importance is considered.

# Examples of basic markdown syntax

## Examples of paragraphs

### Long paragraphs and inline elements
Brewing, in every country, whose soil and climate are congenial to the production of the raw materials, should be ranked among the first objects of its domestic and political economy. If any person doubt the truth of this position, I have only to request him to cast an eye on England, where the brewing capital is estimated at more than fifteen millions sterling; and the gross annual revenue, arising from this capital, at seven million five hundred thousand pounds sterling, including the hop, malt, and extract duties. Notwithstanding this enormous excise of 50 per cent. on the brewing capital, what immense fortunes have been made, and are daily making, in that country, as well as in Ireland and Scotland, by the intelligent and judicious practice of this more than useful art.

### Short paragraphs
The farmer can raise no crop that will pay him better than hops; as, under proper management, he may reasonably expect to clear, of a good year, one hundred dollars per acre. 

Barley will also prove a good crop, if proper attention be paid to seed, soil, and time of sowing.

The merchant will alike find his account in encouraging the brewery, from the many advantages derivable from an extensive export of its produce to the East and West Indies, South America, the Brazils.

## Examples of lists
Sky, or water coolers, in general, are:

-	square vessels
-	of the best two inch pine plank
-	properly jointed
-	from twenty to twenty-five feet square.

But particularly to Russia, where good beer is in great demand; large quantities are annually sent there from England, at a much higher rate, it may be presumed, than we could afford to supply them from this country.

1.	Since writing the Preface, I have been induced to make an addition to this little work, in order to increase its usefulness, by giving the French mode of tanning, as practised by the famous Mr. Seguine.

	Of such importance did the Academy of Arts and Sciences at Paris consider this improvement, that they thought it worth while to appoint a committee of their own members to go down to one of the provinces where this gentleman resides, and there, on the spot, superintend his operations, which they did with minute attention; and it is from the journal of their reports to the academy, that the different processes of tanning leather in this ingenious artist's way are here given:

	-	Brewing without boiling.
	-	Brewing strong beer.
	-	A simple method of giving new beer.
	-	A simple method of preventing beer bursting the bottle.

2. 	This single advantage alone so forcibly recommends its adoption, particularly in a country like ours, where capital is scarce, that further comment is unnecessary. I have also added the Bordeaux method of making and preparing claret wine for shipping, as practised in that city and its vicinity; which practice may possibly hereafter be successfully applied to the red wines of this country.
3. 	As that territory is now in our possession, and its soil and climate peculiarly favourable to the growth of the grape, which is indigenous there, may it not be an object well worth the attention of our government, to encourage and improve the growth of the wine in that section of the union; which wise measure would, probably, in a few years, supply our own consumption, and leave a considerable surplus for exportation. 

All these considerations united seem forcibly to recommend giving the breweries of the United States every possible encouragement and extension. Here, it is but justice to state, that the brewers of New-York deserve much credit for the high improvement they have made in the quality of their malt liquors within a few years, which seem to justify the hope that they will continue these advances to excellence, until they realise the opinion of Combrune and others, that it is possible to produce a malt wine.

## Examples of blockquotes
A new and economical construction of vats for keeping beer, which, in this way, may be rendered fire proof, whilst at the same time possessing the temperature of the best cellars, although above ground.

>The best plan of a well-constructed brewery I conceive to be that of a hollow, or oblong square.

A description of the form and plan of a brewery, distribution of the vessels; the most judicious and convenient manner of placing them, with a view to economy, cleanliness, and effect.

>The best plan of a well-constructed brewery I conceive to be that of a hollow, or oblong square, where all is enclosed by one or two gateways, (the latter the most complete,) parallel to each other. The first gateway, forming the brewery entrance, to pass through the dwelling house; the second, or corresponding gateway, to pass through the opposite side of the square, into an outer yard, well enclosed with walls and sheds, containing cooper's shop, &c. where all the empty casks might be securely preserved from the injury of wind and weather. 

>>The sides of these coolers are generally raised from eighteen inches to two feet; in Europe they are generally leaded on their inside, but this expense may be saved, if they are properly made at first.

>This yard should be further sufficiently large to afford room for a hay reek, firewood, dung, &c. 

Cleanliness being as essential in the brewery as in the dairy, it is of th greatest importance, never to lose sight of it in every part of the operations, and particularly in selecting the ground and soil to place a brewery on. 

## Code blocks
The situation to be preferred should be an elevated one, and the soil either sand or gravel.

	It is of great importance in the preservation of
	beer that the cellars be dry.

Pumping by a hand or a horse power is a poor substitute, as by this means (which we find too common in breweries) the washings of the cellars have time to become putrid.
	
	This is a serious evil, and should in all cases,
	as much as possible, be avoided. It is true, there 
	are times, when a choice of situation cannot be made; 
	in that case, circumstances must be submitted to, 
	and people do the best they can.
	
	The cellars and coolers of the breweries in this 
	country should have a northern aspect, and the
	cellars principally ventilated from east to west.
	The windows on the south side of cellars should be
	always close shut in summer, and only occasionally
	opened in winter; the floors of cellars should be
	paved with either tile or brick, these being more
	susceptible of being kept clean than either pavement
	or flags.

Cleanliness being as essential in the brewery as in the dairy, it is of th greatest importance, never to lose sight of it in every part of the operations, and particularly in selecting the ground and soil to place a brewery on.

## Horizontal rule
Of such importance did the Academy of Arts and Sciences at Paris consider this improvement, that they thought it worth while to appoint a committee of their own members to go down to one of the provinces where this gentleman resides, and there, on the spot, superintend his operations, which they did with minute attention; and it is from the journal of their reports to the academy, that the different processes of tanning leather in this ingenious artist's way are here given.

---

All these considerations united seem forcibly to recommend giving the breweries of the United States every possible encouragement and extension. Here, it is but justice to state, that the brewers of New-York deserve much credit for the high improvement they have made in the quality of their malt liquors within a few years, which seem to justify the hope that they will continue these advances to excellence, until they realise the opinion of Combrune and others, that it is possible to produce a malt wine.

## Images

![Insert your own large image here](https://dl.dropbox.com/s/oq571vn2nhgg8q2/IMG_2567.jpg "Optional title")

A description of the form and plan of a brewery, distribution of the vessels; the most judicious and convenient manner of placing them, with an inline image ![insert your own small image here](https://dl.dropbox.com/s/eus5lzinptdu9n4/TmpImageForMetadata.jpg) with a view to cleanliness, and effect.

# Extensions to basic markdown

## Attribute lists

### Pagebreak {: .pagebreak}

There should be a page break before the heading above.

In Europe they are generally leaded on their inside, but this expense may be saved, if they are properly made at first, and afterwards kept constantly full of water.  

### Floatright

![Insert your own large image here](https://dl.dropbox.com/s/oq571vn2nhgg8q2/IMG_2567.jpg "Optional title"){: .floatright}

In constructing these coolers, all the joints should be paid with white pain before laying, and the sides bolted, and screwed down; the better and easier to effect which, the thickness of the sides may be three inches after the saw; there should be a roofing all round the sides, to protect them from the weather; the bottom of the sky cooler should command the copper back, which should be made to form the cover of the copper, and to hold a complete charge of the same.

## Tables
A description of the form and plan of a brewery, distribution of the vessels; the most judicious and convenient manner of placing them, with a view to economy, cleanliness, and effect.

Code | Room
-----|------
A    | Malt House
B    |Brewery office
C    |Cellars
D    | Sky cooler

Malt house, the best construction of, with proper barley lofts, dropping room, and flooring, how, and in what manner made, and best likely to last.

Code | Room | Notes
-----|-------|-------
A  | Malt House | The dwelling house, vat house, and working store, to form one side of the brewery. 
B  |Brewery office  | Place in the passage of the outer gateway, so that every thing going in and out might be seen by those who are in the office.
C  |Cellars | If these be under ground, it would be very desirable to have them kept sweet and clean by properly constructed sewers
D  | Sky cooler | The sky cooler is, generally, the most elevated vessel in the brewery, and when properly constructed, is of great importance in facilitating both brewing and malting operations, as it usually supplies the whole quantity of water wanted in both.

The best position for placing a brewery and malt house, also the best aspect with different arrangements of the vessels.

End

---

"""

workflow.set_output(html)
Show alert - temporary action - remove soon ?
Title
This workflow now uses some example markdown text from within the workflow
Message
Soon, delete this action and the next action, so this workflow will convert your file that is currently open in Editorial
Button 1
OK
Output Value
Button 2
(don't show)
Output Value
Button 3
(don't show)
Output Value
Show Cancel Button
ON