/**
 * Finish the current PDF stream (writes the deferred length, too)
 */
void PDF_PLOTTER::closePdfStream()
{
    wxASSERT( workFile );

    long stream_len = ftell( workFile );

    if( stream_len < 0 )
    {
        wxASSERT( false );
        return;
    }

    // Rewind the file, read in the page stream and DEFLATE it
    fseek( workFile, 0, SEEK_SET );
    unsigned char *inbuf = new unsigned char[stream_len];

    int rc = fread( inbuf, 1, stream_len, workFile );
    wxASSERT( rc == stream_len );
    (void) rc;

    // We are done with the temporary file, junk it
    fclose( workFile );
    workFile = 0;
    ::wxRemoveFile( workFilename );

    // NULL means memos owns the memory, but provide a hint on optimum size needed.
    wxMemoryOutputStream    memos( NULL, std::max( 2000l, stream_len ) ) ;

    {
        /* Somewhat standard parameters to compress in DEFLATE. The PDF spec is
         * misleading, it says it wants a DEFLATE stream but it really want a ZLIB
         * stream! (a DEFLATE stream would be generated with -15 instead of 15)
         * rc = deflateInit2( &zstrm, Z_BEST_COMPRESSION, Z_DEFLATED, 15,
         *                    8, Z_DEFAULT_STRATEGY );
         */

        wxZlibOutputStream      zos( memos, wxZ_BEST_COMPRESSION, wxZLIB_ZLIB );

        zos.Write( inbuf, stream_len );

        delete[] inbuf;

    }   // flush the zip stream using zos destructor

    wxStreamBuffer* sb = memos.GetOutputStreamBuffer();

    unsigned out_count = sb->Tell();

    fwrite( sb->GetBufferStart(), 1, out_count, outputFile );

    fputs( "endstream\n", outputFile );
    closePdfObject();

    // Writing the deferred length as an indirect object
    startPdfObject( streamLengthHandle );
    fprintf( outputFile, "%u\n", out_count );
    closePdfObject();
}
/**
 * Starts a PDF stream (for the page). Returns the object handle opened
 * Pass -1 (default) for a fresh object. Especially from PDF 1.5 streams
 * can contain a lot of things, but for the moment we only handle page
 * content.
 */
int PDF_PLOTTER::startPdfStream(int handle)
{
    wxASSERT( outputFile );
    wxASSERT( !workFile );
    handle = startPdfObject( handle );

    // This is guaranteed to be handle+1 but needs to be allocated since
    // you could allocate more object during stream preparation
    streamLengthHandle = allocPdfObject();
    fprintf( outputFile,
             "<< /Length %d 0 R /Filter /FlateDecode >>\n" // Length is deferred
             "stream\n", handle + 1 );

    // Open a temporary file to accumulate the stream
    workFilename = filename + wxT(".tmp");
    workFile = wxFopen( workFilename, wxT( "w+b" ));
    wxASSERT( workFile );
    return handle;
}
/**
 * Close the current page in the PDF document (and emit its compressed stream)
 */
void PDF_PLOTTER::ClosePage()
{
    wxASSERT( workFile );

    // Close the page stream (and compress it)
    closePdfStream();

    // Emit the page object and put it in the page list for later
    pageHandles.push_back( startPdfObject() );

    /* Page size is in 1/72 of inch (default user space units)
       Works like the bbox in postscript but there is no need for
       swapping the sizes, since PDF doesn't require a portrait page.
       We use the MediaBox but PDF has lots of other less used boxes
       to use */

    const double BIGPTsPERMIL = 0.072;
    wxSize psPaperSize = pageInfo.GetSizeMils();

    fprintf( outputFile,
             "<<\n"
             "/Type /Page\n"
             "/Parent %d 0 R\n"
             "/Resources <<\n"
             "    /ProcSet [/PDF /Text /ImageC /ImageB]\n"
             "    /Font %d 0 R >>\n"
             "/MediaBox [0 0 %d %d]\n"
             "/Contents %d 0 R\n"
             ">>\n",
             pageTreeHandle,
             fontResDictHandle,
             int( ceil( psPaperSize.x * BIGPTsPERMIL ) ),
             int( ceil( psPaperSize.y * BIGPTsPERMIL ) ),
             pageStreamHandle );
    closePdfObject();

    // Mark the page stream as idle
    pageStreamHandle = 0;
}
bool PDF_PLOTTER::EndPlot()
{
    wxASSERT( outputFile );

    // Close the current page (often the only one)
    ClosePage();

    /* We need to declare the resources we're using (fonts in particular)
       The useful standard one is the Helvetica family. Adding external fonts
       is *very* involved! */
    struct {
        const char *psname;
        const char *rsname;
        int font_handle;
    } fontdefs[4] = {
        { "/Helvetica",             "/KicadFont",   0 },
        { "/Helvetica-Oblique",     "/KicadFontI",  0 },
        { "/Helvetica-Bold",        "/KicadFontB",  0 },
        { "/Helvetica-BoldOblique", "/KicadFontBI", 0 }
    };

    /* Declare the font resources. Since they're builtin fonts, no descriptors (yay!)
       We'll need metrics anyway to do any aligment (these are in the shared with
       the postscript engine) */
    for( int i = 0; i < 4; i++ )
    {
        fontdefs[i].font_handle = startPdfObject();
        fprintf( outputFile,
                 "<< /BaseFont %s\n"
                 "   /Type /Font\n"
                 "   /Subtype /Type1\n"

                 /* Adobe is so Mac-based that the nearest thing to Latin1 is
                    the Windows ANSI encoding! */
                 "   /Encoding /WinAnsiEncoding\n"
                 ">>\n",
                 fontdefs[i].psname );
        closePdfObject();
    }

    // Named font dictionary (was allocated, now we emit it)
    startPdfObject( fontResDictHandle );
    fputs( "<<\n", outputFile );
    for( int i = 0; i < 4; i++ )
    {
        fprintf( outputFile, "    %s %d 0 R\n",
                fontdefs[i].rsname, fontdefs[i].font_handle );
    }
    fputs( ">>\n", outputFile );
    closePdfObject();

    /* The page tree: it's a B-tree but luckily we only have few pages!
       So we use just an array... The handle was allocated at the beginning,
       now we instantiate the corresponding object */
    startPdfObject( pageTreeHandle );
    fputs( "<<\n"
           "/Type /Pages\n"
           "/Kids [\n", outputFile );

    for( unsigned i = 0; i < pageHandles.size(); i++ )
        fprintf( outputFile, "%d 0 R\n", pageHandles[i] );

    fprintf( outputFile,
            "]\n"
            "/Count %ld\n"
             ">>\n", (long) pageHandles.size() );
    closePdfObject();


    // The info dictionary
    int infoDictHandle = startPdfObject();
    char date_buf[250];
    time_t ltime = time( NULL );
    strftime( date_buf, 250, "D:%Y%m%d%H%M%S",
              localtime( &ltime ) );
    fprintf( outputFile,
             "<<\n"
             "/Producer (KiCAD PDF)\n"
             "/CreationDate (%s)\n"
             "/Creator (%s)\n"
             "/Title (%s)\n"
             "/Trapped false\n",
             date_buf,
             TO_UTF8( creator ),
             TO_UTF8( filename ) );

    fputs( ">>\n", outputFile );
    closePdfObject();

    // The catalog, at last
    int catalogHandle = startPdfObject();
    fprintf( outputFile,
             "<<\n"
             "/Type /Catalog\n"
             "/Pages %d 0 R\n"
             "/Version /1.5\n"
             "/PageMode /UseNone\n"
             "/PageLayout /SinglePage\n"
             ">>\n", pageTreeHandle );
    closePdfObject();

    /* Emit the xref table (format is crucial to the byte, each entry must
       be 20 bytes long, and object zero must be done in that way). Also
       the offset must be kept along for the trailer */
    long xref_start = ftell( outputFile );
    fprintf( outputFile,
             "xref\n"
             "0 %ld\n"
             "0000000000 65535 f \n", (long) xrefTable.size() );
    for( unsigned i = 1; i < xrefTable.size(); i++ )
    {
        fprintf( outputFile, "%010ld 00000 n \n", xrefTable[i] );
    }

    // Done the xref, go for the trailer
    fprintf( outputFile,
             "trailer\n"
             "<< /Size %lu /Root %d 0 R /Info %d 0 R >>\n"
             "startxref\n"
             "%ld\n" // The offset we saved before
             "%%%%EOF\n",
             (unsigned long) xrefTable.size(), catalogHandle, infoDictHandle, xref_start );

    fclose( outputFile );
    outputFile = NULL;

    return true;
}