| edisonn@google.com | 2a827e8 | 2012-10-10 15:20:34 +0000 | [diff] [blame] | 1 | /* | 
 | 2 |  * Copyright 2012 Google Inc. | 
 | 3 |  * | 
 | 4 |  * Use of this source code is governed by a BSD-style license that can be | 
 | 5 |  * found in the LICENSE file. | 
 | 6 |  */ | 
 | 7 |  | 
 | 8 | #include "PdfRenderer.h" | 
 | 9 | #include "SkCanvas.h" | 
 | 10 | #include "SkDevice.h" | 
 | 11 | #include "SkPDFDevice.h" | 
 | 12 | #include "SkPDFDocument.h" | 
 | 13 |  | 
 | 14 | namespace sk_tools { | 
 | 15 |  | 
 | 16 | void PdfRenderer::init(SkPicture* pict) { | 
 | 17 |     SkASSERT(NULL == fPicture); | 
 | 18 |     SkASSERT(NULL == fCanvas.get()); | 
 | 19 |     if (fPicture != NULL || NULL != fCanvas.get()) { | 
 | 20 |         return; | 
 | 21 |     } | 
 | 22 |  | 
 | 23 |     SkASSERT(pict != NULL); | 
 | 24 |     if (NULL == pict) { | 
 | 25 |         return; | 
 | 26 |     } | 
 | 27 |  | 
 | 28 |     fPicture = pict; | 
 | 29 |     fCanvas.reset(this->setupCanvas()); | 
 | 30 | } | 
 | 31 |  | 
 | 32 | SkCanvas* PdfRenderer::setupCanvas() { | 
 | 33 |     return this->setupCanvas(fPicture->width(), fPicture->height()); | 
 | 34 | } | 
 | 35 |  | 
 | 36 | SkCanvas* PdfRenderer::setupCanvas(int width, int height) { | 
 | 37 |     SkISize pageSize = SkISize::Make(width, height); | 
 | 38 |     fPDFDevice = SkNEW_ARGS(SkPDFDevice, (pageSize, pageSize, SkMatrix::I())); | 
 | 39 |     return SkNEW_ARGS(SkCanvas, (fPDFDevice)); | 
 | 40 | } | 
 | 41 |  | 
 | 42 | void PdfRenderer::end() { | 
 | 43 |     fPicture = NULL; | 
 | 44 |     fCanvas.reset(NULL); | 
 | 45 |     if (fPDFDevice) { | 
 | 46 |         SkDELETE(fPDFDevice); | 
 | 47 |         fPDFDevice = NULL; | 
 | 48 |     } | 
 | 49 | } | 
 | 50 |  | 
 | 51 | bool PdfRenderer::write(const SkString& path) const { | 
 | 52 |     SkPDFDocument doc; | 
 | 53 |     doc.appendPage(fPDFDevice); | 
 | 54 |     SkFILEWStream stream(path.c_str()); | 
 | 55 |     if (stream.isValid()) { | 
 | 56 |         doc.emitPDF(&stream); | 
 | 57 |         return true; | 
 | 58 |     } | 
 | 59 |     return false; | 
 | 60 | } | 
 | 61 |  | 
 | 62 | void SimplePdfRenderer::render() { | 
 | 63 |     SkASSERT(fCanvas.get() != NULL); | 
 | 64 |     SkASSERT(fPicture != NULL); | 
 | 65 |     if (NULL == fCanvas.get() || NULL == fPicture) { | 
 | 66 |         return; | 
 | 67 |     } | 
 | 68 |  | 
 | 69 |     fCanvas->drawPicture(*fPicture); | 
 | 70 |     fCanvas->flush(); | 
 | 71 | } | 
 | 72 |  | 
 | 73 | } |