Open mariopal opened 8 months ago
Thank! This looks good. I'll test it properly when I have a little more time, hopefully within a week or few. If you want to be "in the git log", you can submit the changes as a PR (otherwise I'll probably just commit something similar myself and attribute it to you in text).
Ok, you can make the commit yourself and if you want, mention me in the text. I also provide a code example to use the new Pdf::new() function, which in addition to the File type, accepts other types that implement Write + Seek traits, such as std::io::Cursor:
//! Example program dumping a PDF to a memory buffer and then to a file
use std::io::Cursor;
use pdf_canvas::{Pdf, BuiltinFont};
use pdf_canvas::graphicsstate::Color;
fn main() {
// let mut document = Pdf::create("example.pdf").expect("Create pdf file");
let mut buf: Vec<u8> = Vec::new();
let fakefile = Cursor::new(&mut buf); //Create fake "file" from buf
let mut document = Pdf::new(fakefile).expect("Create pdf buffer");
let font = BuiltinFont::Helvetica;
let head = "Header";
let foot = "Footer";
// Add a page to the document. This page will be 594 by 841 pt large.
document.render_page(594.0, 841.0, |canvas| {
canvas.set_fill_color(Color::rgb(0, 0, 0))?;
canvas.left_text(80.0 + 320.0*0.0, 761.0 - 530.0*0.0 , font, 9.0, head)?;
canvas.rectangle(80.0 + 320.0*0.0, 755.0 - 530.0*0.0, 108.0, 4.0)?;
canvas.rectangle(184.0 + 320.0*0.0, 647.0 - 530.0*0.0, 4.0, 108.0)?;
canvas.rectangle(80.0 + 320.0*0.0, 647.0 - 530.0*0.0, 108.0, 4.0)?;
canvas.rectangle(80.0 + 320.0*0.0, 647.0 - 530.0*0.0, 4.0, 108.0)?;
canvas.left_text(80.0 + 320.0*0.0, 637.0 - 530.0*0.0 , font, 9.0, foot)?;
canvas.fill()?;
canvas.left_text(80.0 + 320.0*1.0, 761.0 - 530.0*1.0 , font, 9.0, head)?;
canvas.rectangle(80.0 + 320.0*1.0, 755.0 - 530.0*1.0, 108.0, 4.0)?;
canvas.rectangle(184.0 + 320.0*1.0, 647.0 - 530.0*1.0, 4.0, 108.0)?;
canvas.rectangle(80.0 + 320.0*1.0, 647.0 - 530.0*1.0, 108.0, 4.0)?;
canvas.rectangle(80.0 + 320.0*1.0, 647.0 - 530.0*1.0, 4.0, 108.0)?;
canvas.left_text(80.0 + 320.0*1.0, 637.0 - 530.0*1.0 , font, 9.0, foot)?;
canvas.fill()?;
Ok(())
}).expect("Write page");
// Write all pending content, including the trailer and index
document.finish().expect("Finish pdf document");
//Dump the buf in memory to a PDF file
std::fs::write("example.pdf", buf.as_slice()).expect("Create pdf file");
}//main
Instead of always writing the generated PDF to a File, I have modified the code a little so that it dumps the result to any type W that implements Write + Seek:
I only put it here in case you might be interested in adding it to the current code. I think it is compatible with the code that already uses this library. I use it to save the PDF in memory and return it directly as a response to a web request, without going through the file system.