1 /* 2 * Copyright 2013 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 "SkDocument.h" 9 #include "SkPDFDocument.h" 10 #include "SkPDFDevice.h" 11 12 class SkDocument_PDF : public SkDocument { 13 public: 14 SkDocument_PDF(SkWStream* stream, void (*doneProc)(SkWStream*)) 15 : SkDocument(stream, doneProc) { 16 fDoc = SkNEW(SkPDFDocument); 17 fCanvas = NULL; 18 fDevice = NULL; 19 } 20 21 virtual ~SkDocument_PDF() { 22 // subclasses must call close() in their destructors 23 this->close(); 24 } 25 26 protected: 27 virtual SkCanvas* onBeginPage(SkScalar width, SkScalar height, 28 const SkRect& content) SK_OVERRIDE { 29 SkASSERT(NULL == fCanvas); 30 SkASSERT(NULL == fDevice); 31 32 SkISize pageS, contentS; 33 SkMatrix matrix; 34 35 pageS.set(SkScalarRoundToInt(width), SkScalarRoundToInt(height)); 36 contentS.set(SkScalarRoundToInt(content.width()), 37 SkScalarRoundToInt(content.height())); 38 matrix.setTranslate(content.fLeft, content.fTop); 39 40 fDevice = SkNEW_ARGS(SkPDFDevice, (pageS, contentS, matrix)); 41 fCanvas = SkNEW_ARGS(SkCanvas, (fDevice)); 42 return fCanvas; 43 } 44 45 virtual void onEndPage() SK_OVERRIDE { 46 SkASSERT(fCanvas); 47 SkASSERT(fDevice); 48 49 fCanvas->flush(); 50 fDoc->appendPage(fDevice); 51 52 fCanvas->unref(); 53 fDevice->unref(); 54 55 fCanvas = NULL; 56 fDevice = NULL; 57 } 58 59 virtual void onClose(SkWStream* stream) SK_OVERRIDE { 60 SkASSERT(NULL == fCanvas); 61 SkASSERT(NULL == fDevice); 62 63 fDoc->emitPDF(stream); 64 SkDELETE(fDoc); 65 fDoc = NULL; 66 } 67 68 private: 69 SkPDFDocument* fDoc; 70 SkPDFDevice* fDevice; 71 SkCanvas* fCanvas; 72 }; 73 74 /////////////////////////////////////////////////////////////////////////////// 75 76 SkDocument* SkDocument::CreatePDF(SkWStream* stream, void (*done)(SkWStream*)) { 77 return stream ? SkNEW_ARGS(SkDocument_PDF, (stream, done)) : NULL; 78 } 79 80 static void delete_wstream(SkWStream* stream) { 81 SkDELETE(stream); 82 } 83 84 SkDocument* SkDocument::CreatePDF(const char path[]) { 85 SkFILEWStream* stream = SkNEW_ARGS(SkFILEWStream, (path)); 86 if (!stream->isValid()) { 87 SkDELETE(stream); 88 return NULL; 89 } 90 return SkNEW_ARGS(SkDocument_PDF, (stream, delete_wstream)); 91 } 92