Construct a single page PDF from the provided page in memory
165441
def _single_page_pdf(page):
    """"""
    pdf = Pdf.new()
    pdf.pages.append(page)
    bio = BytesIO()
    pdf.save(bio)
    bio.seek(0)
    return bio.read()
1317631
def serve_concatenated_pdf_from_memory(
        pdf_plans: Iterable[PdfPlan],
        start_recto: bool = True,
        offered_filename: str = "crate_download.pdf") -> HttpResponse:
    
    pdf = get_concatenated_pdf_in_memory(pdf_plans, start_recto=start_recto)
    return serve_buffer(pdf,
                        offered_filename=offered_filename,
                        content_type=MimeType.PDF,
                        as_attachment=False,
                        as_inline=True)
273383
def pdf_remove(source: str, pages: [str], output: str = None):
    
    if output is not None and os.path.isfile(output):
        if overwrite_dlg(output) is False:
            return

    writer = PdfFileWriter()
    srcfile = open(source, "rb")
    srcreader = PdfFileReader(srcfile)

    # Add pages, leave out removed pages
    pages = parse_rangearg(pages, len(srcreader.pages))
    for pagenr, page in enumerate(srcreader.pages):
        if pagenr not in pages:
            writer.addPage(page)

    # Open output file or temporary file for writing
    if output is None:
        outfile = NamedTemporaryFile(delete=False)
    else:
        outfile = open(output, "wb")

    # Write file and close
    writer.write(outfile)
    srcfile.close()
    outfile.close()

    # Move temporary file to source
    if output is None:
        if overwrite_dlg(source):
            os.remove(source)
            move(outfile.name, source)
        else:
            os.remove(outfile)
1246729
def write_pagerange(self, pagerange, prefix=''):
        
        writer = PdfFileWriter()
        slug = "".join([c for c in pagerange['title'].replace(" ", "-") if c.isalnum() or c == "-"])
        write_to_path = os.path.sep.join([self.directory, "{}{}.pdf".format(prefix, slug)])
        for page in range(pagerange['page_start'], pagerange['page_end']):
            writer.addPage(self.pdf.getPage(page))
            writer.removeLinks()                   # must be done every page
        with open(write_to_path, 'wb') as outfile:
            writer.write(outfile)
        return write_to_path
673195
def _pdf(self, xloc, dist, cache):
        """"""
        return evaluation.evaluate_density(dist, -xloc, cache=cache)
914511
def build_document(html_content, base_href=None):
    """"""
    assert html_content is not None

    if isinstance(html_content, unicode):
        html_content = html_content.encode("utf8", "xmlcharrefreplace")

    try:
        document = document_fromstring(html_content, parser=UTF8_PARSER)
    except (ParserError, XMLSyntaxError):
        raise ValueError("Failed to parse document contents.")

    if base_href:
        document.make_links_absolute(base_href, resolve_base_href=True)
    else:
        document.resolve_base_href()

    return document
1355966
public static void main (String args[]) {
		if (args.length != 3) {
			System.err.println("arguments: srcfile destfile pages");
		}
		else {
			try {
				int pages = Integer.parseInt(args[2]);
				if (pages < 2 || pages > 8) {
					throw new DocumentException("You can't have " + pages + " pages on one page (minimum 2; maximum 8).");
				}
                
				float x1 = 30f;
				float x2 = 280f;
				float x3 = 320f;
				float x4 = 565f;
                
				float[] y1 = new float[pages];
				float[] y2 = new float[pages];
                
				float height = (778f - (20f * (pages - 1))) / pages;
				y1[0] = 812f;
				y2[0] = 812f - height;
                
				for (int i = 1; i < pages; i++) {
					y1[i] = y2[i - 1] - 20f;
					y2[i] = y1[i] - height;
				}
                
				// we create a reader for a certain document
				PdfReader reader = new PdfReader(args[0]);
				// we retrieve the total number of pages
				int n = reader.getNumberOfPages();
				System.out.println("There are " + n + " pages in the original file.");
                
				// step 1: creation of a document-object
				Document document = new Document(PageSize.A4);
				// step 2: we create a writer that listens to the document
				PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(args[1]));
				// step 3: we open the document
				document.open();
				PdfContentByte cb = writer.getDirectContent();
				PdfImportedPage page;
				int rotation;
				int i = 0;
				int p = 0;
				// step 4: we add content
				while (i < n) {
					i++;
					Rectangle rect = reader.getPageSizeWithRotation(i);
					float factorx = (x2 - x1) / rect.getWidth();
					float factory = (y1[p] - y2[p]) / rect.getHeight();
					float factor = (factorx < factory ? factorx : factory);
					float dx = (factorx == factor ? 0f : ((x2 - x1) - rect.getWidth() * factor) / 2f);
					float dy = (factory == factor ? 0f : ((y1[p] - y2[p]) - rect.getHeight() * factor) / 2f);
					page = writer.getImportedPage(reader, i);
					rotation = reader.getPageRotation(i);
					if (rotation == 90 || rotation == 270) {
						cb.addTemplate(page, 0, -factor, factor, 0, x1 + dx, y2[p] + dy + rect.getHeight() * factor);
					}
					else {
						cb.addTemplate(page, factor, 0, 0, factor, x1 + dx, y2[p] + dy);
					}
					cb.setRGBColorStroke(0xC0, 0xC0, 0xC0);
					cb.rectangle(x3 - 5f, y2[p] - 5f, x4 - x3 + 10f, y1[p] - y2[p] + 10f);
					for (float l = y1[p] - 19; l > y2[p]; l -= 16) {
						cb.moveTo(x3, l);
						cb.lineTo(x4, l);
					}
					cb.rectangle(x1 + dx, y2[p] + dy, rect.getWidth() * factor, rect.getHeight() * factor);
					cb.stroke();
					System.out.println("Processed page " + i);
					p++;
					if (p == pages) {
						p = 0;
						document.newPage();
					}
				}
				// step 5: we close the document
				document.close();
			}
			catch(Exception e) {
				System.err.println(e.getClass().getName() + ": " + e.getMessage());
			}
		}
    }
1366816
def create_page(title, space, parrent_page_id=nil)
            params = { 'type' => 'page',
                'title' => title,
                'space' => {'key' => space},
                'body' => {
                    'storage' => {
                        'value' => ("#{ @body_message.to_json.gsub("&&", "&amp;&amp;").gsub(/\\u001b.../, "   ") }").force_encoding('UTF-8'),
                        'representation' => 'storage'
                        }
                    }
                }
            if parrent_page_id
                params['ancestors'] = [{'type' => 'page', 'id' => parrent_page_id}]
            end

            uri = URI.parse(@base_url)
            https = Net::HTTP.new(uri.host,uri.port)
            https.use_ssl = true
            # https.set_debug_output $stderr
            req = Net::HTTP::Post.new(uri.path, initheader = {'Content-Type' =>'application/json'})
            req.basic_auth(@user, @password)
            req['Accept'] = 'application/json'
            req.body = "#{params.to_json}"
            response = https.request(req)
            response = JSON.parse(response.body)
            if response["statusCode"] == 400
                puts response.inspect
                puts req.body.inspect
                puts "Create page: Error reporting to confluence: #{response["message"]}"
                raise "Create page: Error reporting to confluence: #{response["message"]}"
            else
                puts "Reported page creation."
            end
        end
246113
def page(self, attr=None, fill=u' '):
        '''
        if attr is None:
            attr = self.attr
        if len(fill) != 1:
            raise ValueError
        info = CONSOLE_SCREEN_BUFFER_INFO()
        self.GetConsoleScreenBufferInfo(self.hout, byref(info))
        if info.dwCursorPosition.X != 0 or info.dwCursorPosition.Y != 0:
            self.SetConsoleCursorPosition(self.hout, self.fixcoord(0, 0))

        w = info.dwSize.X
        n = DWORD(0)
        for y in range(info.dwSize.Y):
            self.FillConsoleOutputAttribute(self.hout, attr, 
                                            w, self.fixcoord(0, y), byref(n))
            self.FillConsoleOutputCharacterW(self.hout, ord(fill[0]), 
                                             w, self.fixcoord(0, y), byref(n))

        self.attr = attr
710226
def download(self, data, filename, content_type="application/pdf"):
        
        self.request.response.setHeader(
            "Content-Disposition", "inline; filename=%s" % filename)
        self.request.response.setHeader("Content-Type", content_type)
        self.request.response.setHeader("Content-Length", len(data))
        self.request.response.setHeader("Cache-Control", "no-store")
        self.request.response.setHeader("Pragma", "no-cache")
        self.request.response.write(data)
134712
def create_page(self, space, title, body, parent_id=None, type='page'):
        
        log.info('Creating {type} "{space}" -> "{title}"'.format(space=space, title=title, type=type))
        url = 'rest/api/content/'
        data = {
            'type': type,
            'title': title,
            'space': {'key': space},
            'body': {'storage': {
                'value': body,
                'representation': 'storage'}}}
        if parent_id:
            data['ancestors'] = [{'type': type, 'id': parent_id}]
        return self.post(url, data=data)
489033
def pdf_from_string(string, output_file = '-')
      with_timeout do
        pdf = initialize_pdf_from_string(string, output_file, {:output_to_log_file => false})
        pdf.close_write
        result = pdf.gets(nil)
        pdf.close_read
        result.force_encoding('BINARY') if RUBY_VERSION >= "1.9"

        result
      end
    end
1243363
def fetch(url, binary, outfile, noprint, rendered):
	'''
	
	'''
	with chrome_context.ChromeContext(binary=binary) as cr:
		resp = cr.blocking_navigate_and_get_source(url)
		if rendered:
			resp['content'] = cr.get_rendered_page_source()
			resp['binary'] = False
			resp['mimie'] = 'text/html'

	if not noprint:
		if resp['binary'] is False:
			print(resp['content'])
		else:
			print("Response is a binary file")
			print("Cannot print!")

	if outfile:
		with open(outfile, "wb") as fp:
			if resp['binary']:
				fp.write(resp['content'])
			else:
				fp.write(resp['content'].encode("UTF-8"))
611752
function renderPDF(params, cb) {
  var template = params.template;
  var session = params.session;
  var form = params.form;
  var submission = params.submission;
  submission.formName = form.name;
  var studioLocation = params.location;
  var generationTimestamp = params.generationTimestamp || Date.now();

  var page;

  session.createPage()
    .then(function(_page) {
      logger.debug('page created');
      page = _page;
      // A4 aspect ratio
      page.property('paperSize', {format: 'A4'})
        .then(function() {
          logger.debug('page aspect ratio set');

          //Can't load css files over https. Needs to be http.
          if (typeof(studioLocation) === "string") {
            studioLocation = studioLocation.replace("https://", "http://");
          }
          form = processForm(form, submission);
          var html = template({
            form: form.form,
            location: studioLocation,
            subexport: form.sub,
            js: params.js,
            css: params.css
          });

          // inject html as we don't have a server to serve html to phantom
          page.setContent(html, null)
            .then(function(status) {
              logger.debug('content set. status', status);

              var file = path.join(params.pdfExportDir, form.sub.formSubmittedAgainst._id + '_' + form.sub._id + '_' + generationTimestamp + '.pdf');
              page.render(file)
                .then(function() {
                  logger.info('Rendered pdf:', {file: file});
                  page.close();
                  page = null;

                  destroyPhantomSession(session, function() {
                    return cb(null, file);
                  });
                });
            });
        });
    })
    .catch(function(e1) {
      logger.error('Exception rendering pdf', {exception: e1});
      try {
        if (page) {
          page.close();
        }
      } catch (e2) {
        // silent
        logger.warn('Error closing page after phantom exception', {exception: e2});
      }
      return cb('Exception rendering pdf:' + e1.toString());
    });
}
354915
def generate_page_object(page_name, url):
    ""

    # Attempt to extract partial URL for verification.
    url_with_path = u('^.*//[^/]+([^?]+)?|$')
    try:
        match = re.match(url_with_path, url)
        partial_url = match.group(1)
        print("Using partial URL for location verification. ", partial_url)
    except:
        # use full url since we couldn't extract a partial.
        partial_url = url
        print("Could not find usable partial url, using full url.", url)

    # Attempt to map input objects.
    print("Processing page source...")
    response = urllib2.urlopen(url)
    html = response.read()
    input_tags_expr = u('<\s*input[^>]*>')
    input_tag_iter = re.finditer(input_tags_expr, html, re.IGNORECASE)

    objectmap = ""
    print("Creating object map for <input> tags...")
    for input_tag_match in input_tag_iter:
        if not "hidden" in input_tag_match.group(0):
            try:
                print("processing", input_tag_match.group(0))
                obj_map_entry = _process_input_tag(input_tag_match.group(0))
                objectmap += u("    ") + obj_map_entry + "\n"
            except Exception as e:
                print(e)
                # we failed to process it, nothing more we can do.
                pass

    return _page_object_template_.contents.format(date=datetime.now(),
                                                  url=url,
                                                  pagename=page_name,
                                                  partialurl=partial_url,
                                                  objectmap=objectmap)
628956
function(connectionInfo, processPagedResults) {
  var args = {
    page: {value: 1},//{value: 25},
    pageSize: {value: 200}
  };
  // set a default function if none is provided
  if (!processPagedResults) {
    processPagedResults = function(pagedData, previousData){
      if (previousData && previousData.length>0) {
        if (pagedData.consignments.length>0) {
          log.debug('previousData: ', previousData.length);
          pagedData.consignments = pagedData.consignments.concat(previousData);
          log.debug('combined: ', pagedData.consignments.length);
        }
        else {
          pagedData.consignments = previousData;
        }
      }
      return Promise.resolve(pagedData.consignments);
    };
  }
  return utils.processPagesRecursively(args, connectionInfo, fetchStockOrdersForSuppliers, processPagedResults);
}
957671
def generate_pages_by_file():
    """"""
    from veripress import app
    from veripress.model import storage
    from veripress.model.parsers import get_standard_format_name
    from veripress.helpers import traverse_directory

    deploy_dir = get_deploy_dir()

    def copy_file(src, dst):
        makedirs(os.path.dirname(dst), mode=0o755, exist_ok=True)
        shutil.copyfile(src, dst)

    with app.app_context(), app.test_client() as client:
        root_path = os.path.join(app.instance_path, 'pages')
        for path in traverse_directory(root_path):
            # e.g. 'a/b/c/index.md'
            rel_path = os.path.relpath(path, root_path)
            # e.g. ('a/b/c/index', '.md')
            filename, ext = os.path.splitext(rel_path)
            if get_standard_format_name(ext[1:]) is not None:
                # is source of custom page
                rel_url = filename.replace(os.path.sep, '/') + '.html'
                page = storage.get_page(rel_url, include_draft=False)
                if page is not None:
                    # it's not a draft, so generate the html page
                    makedirs(os.path.join(deploy_dir,
                                          os.path.dirname(rel_path)),
                             mode=0o755, exist_ok=True)
                    with open(os.path.join(deploy_dir, filename + '.html'),
                              'wb') as f:
                        f.write(client.get('/' + rel_url).data)
                if app.config['PAGE_SOURCE_ACCESSIBLE']:
                    copy_file(path, os.path.join(deploy_dir, rel_path))
            else:
                # is other direct files
                copy_file(path, os.path.join(deploy_dir, rel_path))