Skip to content

Instantly share code, notes, and snippets.

@spacetc62
Forked from expectedbehavior/MainWindow.xaml.cs
Created October 25, 2010 16:55
Show Gist options
  • Save spacetc62/645294 to your computer and use it in GitHub Desktop.
Save spacetc62/645294 to your computer and use it in GitHub Desktop.
/*
* Doc Raptor simple PHP example
* requires pecl_http extension
*
* This is a simple example of creating an excel file and saving it
* using Doc Raptor
*
* For other usage and examples, visit:
* http://docraptor.com/examples
*
* Doc Raptor http://docraptor.com
* Expected Behavior http://www.expectedbehavior.com
*/
<?php
$api_key = "YOUR_API_KEY_HERE";
$url = "https://docraptor.com/docs?user_credentials=$api_key";
$document_content = "<table><tr><td>Cell</td></tr></table>";
$request = new HTTPRequest($url, HTTP_METH_POST);
$request->setPostFields(array('doc[document_content]' => $document_content,
'doc[document_type]' => 'xls',
'doc[name]' => 'my_doc.xls',
'doc[test]' => 'true'));
$request->send();
$file = fopen ("my_excel_doc.xls", "w");
fwrite($file, $request->getResponseBody());
fclose ($file);
?>
require 'rubygems'
require 'doc_raptor'
DocRaptor.api_key "YOUR_API_KEY_HERE"
xls_html = "<table name='My First Sheet'><tr><td>Cell 1</td><td>Cell 2</td></tr></table>"
File.open("docraptor_sample.xls", "w+") do |f|
f.write DocRaptor.create(:document_content => xls_html,
:name => "docraptor_sample.xls",
:document_type => "xls",
:test => true)
end
pdf_html = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html lang="en"><body><a href="http://google.com">google</a></body></html>'
File.open("docraptor_sample.pdf", "w+") do |f|
f.write DocRaptor.create(:document_content => pdf_html,
:name => "docraptor_sample.pdf",
:document_type => "pdf",
:test => true)
end
#This example will create a sample excel document with the authentication information as part of the POST data
curl -H "Content-Type:application/json" -d'{"user_credentials":"YOUR_API_KEY_HERE", "doc":{"name":"docraptor_sample.xls", "document_type":"xls", "test":"true", "document_content":"<table name=\"My First Sheet\"><tr><td>Cell 1</td><td>Cell 2</td></tr></table>"}}' http://docraptor.com/docs > docraptor_sample.xls
#This example will create a sample excel document with the authentication information as part of the URL
curl -H "Content-Type:application/json" -d'{"doc":{"name":"docraptor_sample.xls", "document_type":"xls", "test":"true", "document_content":"<table name=\"My First Sheet\"><tr><td>Cell 1</td><td>Cell 2</td></tr></table>"}}' http://docraptor.com/docs?user_credentials=YOUR_API_KEY_HERE > docraptor_sample.xls
#This example will create a sample pdf document with the authentication information as part of the POST data
curl -H "Content-Type:application/json" -d'{"user_credentials":"YOUR_API_KEY_HERE", "doc":{"name":"docraptor_sample.pdf", "document_type":"pdf", "test":"true", "document_content":"<html><body>Text in a PDF</body></html>"}}' http://docraptor.com/docs > docraptor_sample.pdf
#This example will create a sample pdf document with the authentication information as part of the URL
curl -H "Content-Type:application/json" -d'{"doc":{"name":"docraptor_sample.pdf", "document_type":"pdf", "test":"true", "document_content":"<html><body>Text in a PDF</body></html>"}}' http://docraptor.com/docs?user_credentials=YOUR_API_KEY_HERE > docraptor_sample.pdf
%table{ :name => "Excel Example" }
%tr{ :style => "font-weight:bold;" }
%td Document Name
%td Document Type
%td Test Mode
%td Result Url
- @examples.each do |example|
%tr
%td=example.document_name
%td=example.document_type
%td=example.test
%td{ :style => "color:blue;" }=path_to_url(example.document.url)
// this function is based on code found:
// http://www.filamentgroup.com/lab/jquery_plugin_for_requesting_ajax_like_file_downloads/
// to easily make a form and POST it
var download = function(url, data, method){
//url and data options required
if( url && data ){
jQuery('<form style="display: none" id="dr_submission" action="' + url
+ '" method="' + (method||'post') + '">'
+ '</form>').appendTo('body');
//credentials
jQuery('form#dr_submission').append('<textarea name="user_credentials"></textarea>');
jQuery('form#dr_submission textarea[name=user_credentials]').val(data.user_credentials);
//doc values
for(var key in data.doc) {
jQuery('form#dr_submission').append('<textarea name="doc['+key+']"></textarea>');
jQuery('form#dr_submission textarea[name="doc['+key+']"]').val(data.doc[key]);
}
//submit the form
if(confirm("press ok")) {jQuery('form#dr_submission').submit().remove(); }
};
};
// setup the string represeting the html we want to submit
var content = '<table name="foo"><tr><td>word up</td></tr></table><textarea>Foo&nbsp;&nbsp;&trade;&nbsp;&nbsp;Bar</textarea><p>What happens to +\'s?</p>';
var data = {
doc: {
test: true,
document_type: 'pdf',
name: 'adoc',
document_content: content,
strict: 'none'
},
user_credentials: "YOUR_API_KEY"
};
// this drops a form on the page and submits, which will result in a download dialog popping up
download("http://docraptor.com/docs.xls", data);
// this function is based on code found:
// http://www.filamentgroup.com/lab/jquery_plugin_for_requesting_ajax_like_file_downloads/
// to easily make a form and POST it
var download = function(url, data, method){
//url and data options required
if(url && data){
//data can be string of parameters or array/object
data = jQuery.param(data);
// make the entire request against a url instead of as form params
url += '?' + data
//send request
jQuery('<form style="display: none" action="' + url
+ '" method="' + (method||'post') + '">'
+ '</form>').appendTo('body').submit().remove();
}
};
// setup the string represeting the html we want to submit
var content = '<table name="foo"><tr><td>word up</td></tr></table><textarea>Foo&nbsp;&nbsp;&trade;&nbsp;&nbsp;Bar</textarea>';
var data = {
doc: {
test: true,
document_type: 'pdf',
name: 'adoc',
document_content: content,
strict: 'none'
},
user_credentials: 'YOUR_API_KEY'
};
// this drops a form on the page and submits, which will result in a download dialog popping up
download("http://docraptor.com/docs", data);
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Web;
using System.Windows;
using Microsoft.Win32;
namespace DocRaptorExample
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private const string PostFormat = "doc[document_content]={0}&doc[name]={1}&doc[document_type]={2}&doc[test]={3}";
private const string ApiKey = "YOUR_API_KEY_HERE";
private static string DocRaptorUrl = String.Format("https://docraptor.com/docs?user_credentials={0}", ApiKey);
public MainWindow()
{
InitializeComponent();
SampleExcelContentClick(null, null);
}
private void SampleExcelContentClick(object sender, RoutedEventArgs e)
{
_DocumentContent.Text =
"<table name='My First Sheet'>\n <tr>\n <td>Cell 1</td>\n <td>Cell 2</td>\n </tr>\n</table>";
}
private void SamplePDFContentClick(object sender, RoutedEventArgs e)
{ _DocumentContent.Text = "<html>\n <body>\n Some Text in a PDF\n </body>\n</html>"; }
private void CreateExcelClick(object sender, RoutedEventArgs e)
{ CreateDocument(_DocumentContent.Text, "xls", true); }
private void CreatePDFClick(object sender, RoutedEventArgs e)
{ CreateDocument(_DocumentContent.Text, "pdf", true); }
public static void CreateDocument(string documentContent, string type, bool test)
{
var sfd = new SaveFileDialog();
if (sfd.ShowDialog() != true) { return; }
var postData = String.Format(PostFormat, HttpUtility.UrlEncode(documentContent),
HttpUtility.UrlEncode(sfd.SafeFileName),
HttpUtility.UrlEncode(type),
HttpUtility.UrlEncode(test.ToString().ToLower()));
var byteArray = Encoding.UTF8.GetBytes(postData);
var request = (HttpWebRequest)WebRequest.Create(DocRaptorUrl);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
using (var dataStream = request.GetRequestStream())
{ dataStream.Write(byteArray, 0, byteArray.Length); }
try
{
var response = request.GetResponse();
using (var dataStream = response.GetResponseStream())
{
using (Stream file = File.OpenWrite(sfd.FileName))
{ CopyStream(dataStream, file); }
}
MessageBox.Show("File Saved", "Success");
}
catch (WebException e)
{
if (e.Status == WebExceptionStatus.ProtocolError)
{
var response = (HttpWebResponse)e.Response;
string errorResponse;
using (var dataStream = response.GetResponseStream())
{
using (var reader = new StreamReader(dataStream))
{ errorResponse = reader.ReadToEnd(); }
}
MessageBox.Show(errorResponse, String.Format("{0} - {1}", response.StatusCode, response.StatusDescription));
}
else
{
MessageBox.Show(e.Message, "Error");
}
}
}
public static void CopyStream(Stream input, Stream output)
{
var buffer = new byte[8 * 1024];
int len;
while ((len = input.Read(buffer, 0, buffer.Length)) > 0)
{ output.Write(buffer, 0, len); }
}
private void OpenLinkClick(object sender, RoutedEventArgs e)
{ System.Diagnostics.Process.Start(((System.Windows.Documents.Hyperlink)sender).NavigateUri.ToString()); }
}
}
// this function is based on code found:
// http://www.filamentgroup.com/lab/jquery_plugin_for_requesting_ajax_like_file_downloads/
// to easily make a form and POST it
var download = function(url, data, method){
//url and data options required
if( url && data ){
//data can be string of parameters or array/object
data = typeof data == 'string' ? data : $H(data).toQueryString();
//split params into form inputs
var inputs = '';
data.split('&').each(function(s){
var pair = s.split('=');
var name = pair.shift();
var value = pair.join("=");
inputs+='<textarea name="'+ name +'">'+ value +'</textarea>';
});
//send request
$$('body')[0].insert('<form id="DocRaptor-example" style="display: none" action="' + url
+ '" method="' + (method||'post') + '">'
+ inputs +
'</form>');
$('DocRaptor-example').submit();
$('DocRaptor-example').remove();
};
};
// setup the string represeting the table we want to submit
var content = '<table name="foo"><tr><td>word up</td></tr></table>';
// this drops a form on the page and submits, which will result in a download dialog popping up
download("http://docraptor.com/docs.xls",
"doc[document_content]=" + content +
"&doc[name]=adoc&user_credentials=<YOUR_API_KEY_HERE>");
class ExamplesController < ApplicationController
def index
@examples = Example.all
# Don't forget to reigster the xls/pdf mime types in config/initializers/mime_types.rb
respond_to do |format|
format.html
format.xls { doc_raptor_send }
format.pdf { doc_raptor_send }
end
end
def doc_raptor_send(options = { })
default_options = {
:name => controller_name,
:document_type => request.format.to_sym,
:test => ! Rails.env.production?,
}
options = default_options.merge(options)
options[:document_content] ||= render_to_string
ext = options[:document_type].to_sym
response = DocRaptor.create(options)
if response.code == 200
send_data response, :filename => "#{options[:name]}.#{ext}", :type => ext
else
render :inline => response.body, :status => response.code
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment