KiCad PCB EDA Suite
PDF_plotter.cpp
Go to the documentation of this file.
1 
6 /*
7  * This program source code file is part of KiCad, a free EDA CAD application.
8  *
9  * Copyright (C) 1992-2012 Lorenzo Marcantonio, l.marcantonio@logossrl.com
10  * Copyright (C) 1992-2017 KiCad Developers, see AUTHORS.txt for contributors.
11  *
12  * This program is free software; you can redistribute it and/or
13  * modify it under the terms of the GNU General Public License
14  * as published by the Free Software Foundation; either version 2
15  * of the License, or (at your option) any later version.
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with this program; if not, you may find one here:
24  * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
25  * or you may search the http://www.gnu.org website for the version 2 license,
26  * or you may write to the Free Software Foundation, Inc.,
27  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
28  */
29 
30 #include <fctsys.h>
31 #include <pgm_base.h>
32 #include <trigo.h>
33 #include <eda_base_frame.h>
34 #include <base_struct.h>
35 #include <common.h>
36 #include <plotter.h>
37 #include <macros.h>
38 #include <kicad_string.h>
39 #include <wx/zstream.h>
40 #include <wx/mstream.h>
41 #include <math/util.h> // for KiROUND
42 
43 
44 /*
45  * Open or create the plot file aFullFilename
46  * return true if success, false if the file cannot be created/opened
47  *
48  * Opens the PDF file in binary mode
49  */
50 bool PDF_PLOTTER::OpenFile( const wxString& aFullFilename )
51 {
52  filename = aFullFilename;
53 
54  wxASSERT( !outputFile );
55 
56  // Open the PDF file in binary mode
57  outputFile = wxFopen( filename, wxT( "wb" ) );
58 
59  if( outputFile == NULL )
60  return false ;
61 
62  return true;
63 }
64 
65 void PDF_PLOTTER::SetPageSettings( const PAGE_INFO& aPageSettings )
66 {
67  pageInfo = aPageSettings;
68 }
69 
70 void PDF_PLOTTER::SetViewport( const wxPoint& aOffset, double aIusPerDecimil,
71  double aScale, bool aMirror )
72 {
73  m_plotMirror = aMirror;
74  plotOffset = aOffset;
75  plotScale = aScale;
76  m_IUsPerDecimil = aIusPerDecimil;
77 
78  // The CTM is set to 1 user unit per decimil
79  iuPerDeviceUnit = 1.0 / aIusPerDecimil;
80 
81  SetDefaultLineWidth( 100 / iuPerDeviceUnit ); // arbitrary default
82 
83  /* The paper size in this engined is handled page by page
84  Look in the StartPage function */
85 }
86 
87 
96 void PDF_PLOTTER::SetCurrentLineWidth( int width, void* aData )
97 {
98  wxASSERT( workFile );
99  int pen_width;
100 
101  if( width > 0 )
102  pen_width = width;
103  else if( width == 0 )
104  pen_width = 1;
105  else
106  pen_width = defaultPenWidth;
107 
108  if( pen_width != currentPenWidth )
109  fprintf( workFile, "%g w\n",
110  userToDeviceSize( pen_width ) );
111 
112  currentPenWidth = pen_width;
113 }
114 
115 
125 void PDF_PLOTTER::emitSetRGBColor( double r, double g, double b )
126 {
127  wxASSERT( workFile );
128  fprintf( workFile, "%g %g %g rg %g %g %g RG\n",
129  r, g, b, r, g, b );
130 }
131 
136 {
137  wxASSERT( workFile );
138  switch( dashed )
139  {
141  fprintf( workFile, "[%d %d] 0 d\n",
142  (int) GetDashMarkLenIU(), (int) GetDashGapLenIU() );
143  break;
144  case PLOT_DASH_TYPE::DOT:
145  fprintf( workFile, "[%d %d] 0 d\n",
146  (int) GetDotMarkLenIU(), (int) GetDashGapLenIU() );
147  break;
149  fprintf( workFile, "[%d %d %d %d] 0 d\n",
150  (int) GetDashMarkLenIU(), (int) GetDashGapLenIU(),
151  (int) GetDotMarkLenIU(), (int) GetDashGapLenIU() );
152  break;
153  default:
154  fputs( "[] 0 d\n", workFile );
155  }
156 }
157 
158 
162 void PDF_PLOTTER::Rect( const wxPoint& p1, const wxPoint& p2, FILL_T fill, int width )
163 {
164  wxASSERT( workFile );
165  DPOINT p1_dev = userToDeviceCoordinates( p1 );
166  DPOINT p2_dev = userToDeviceCoordinates( p2 );
167 
168  SetCurrentLineWidth( width );
169  fprintf( workFile, "%g %g %g %g re %c\n", p1_dev.x, p1_dev.y,
170  p2_dev.x - p1_dev.x, p2_dev.y - p1_dev.y,
171  fill == NO_FILL ? 'S' : 'B' );
172 }
173 
174 
178 void PDF_PLOTTER::Circle( const wxPoint& pos, int diametre, FILL_T aFill, int width )
179 {
180  wxASSERT( workFile );
181  DPOINT pos_dev = userToDeviceCoordinates( pos );
182  double radius = userToDeviceSize( diametre / 2.0 );
183 
184  /* OK. Here's a trick. PDF doesn't support circles or circular angles, that's
185  a fact. You'll have to do with cubic beziers. These *can't* represent
186  circular arcs (NURBS can, beziers don't). But there is a widely known
187  approximation which is really good
188  */
189 
190  SetCurrentLineWidth( width );
191 
192  // If diameter is less than width, switch to filled mode
193  if( aFill == NO_FILL && diametre < width )
194  {
195  aFill = FILLED_SHAPE;
196  SetCurrentLineWidth( 0 );
197 
198  radius = userToDeviceSize( ( diametre / 2.0 ) + ( width / 2.0 ) );
199  }
200 
201  double magic = radius * 0.551784; // You don't want to know where this come from
202 
203  // This is the convex hull for the bezier approximated circle
204  fprintf( workFile, "%g %g m "
205  "%g %g %g %g %g %g c "
206  "%g %g %g %g %g %g c "
207  "%g %g %g %g %g %g c "
208  "%g %g %g %g %g %g c %c\n",
209  pos_dev.x - radius, pos_dev.y,
210 
211  pos_dev.x - radius, pos_dev.y + magic,
212  pos_dev.x - magic, pos_dev.y + radius,
213  pos_dev.x, pos_dev.y + radius,
214 
215  pos_dev.x + magic, pos_dev.y + radius,
216  pos_dev.x + radius, pos_dev.y + magic,
217  pos_dev.x + radius, pos_dev.y,
218 
219  pos_dev.x + radius, pos_dev.y - magic,
220  pos_dev.x + magic, pos_dev.y - radius,
221  pos_dev.x, pos_dev.y - radius,
222 
223  pos_dev.x - magic, pos_dev.y - radius,
224  pos_dev.x - radius, pos_dev.y - magic,
225  pos_dev.x - radius, pos_dev.y,
226 
227  aFill == NO_FILL ? 's' : 'b' );
228 }
229 
230 
235 void PDF_PLOTTER::Arc( const wxPoint& centre, double StAngle, double EndAngle, int radius,
236  FILL_T fill, int width )
237 {
238  wxASSERT( workFile );
239  if( radius <= 0 )
240  {
241  Circle( centre, width, FILLED_SHAPE, 0 );
242  return;
243  }
244 
245  /* Arcs are not so easily approximated by beziers (in the general case),
246  so we approximate them in the old way */
247  wxPoint start, end;
248  const int delta = 50; // increment (in 0.1 degrees) to draw circles
249 
250  if( StAngle > EndAngle )
251  std::swap( StAngle, EndAngle );
252 
253  SetCurrentLineWidth( width );
254 
255  // Usual trig arc plotting routine...
256  start.x = centre.x + KiROUND( cosdecideg( radius, -StAngle ) );
257  start.y = centre.y + KiROUND( sindecideg( radius, -StAngle ) );
258  DPOINT pos_dev = userToDeviceCoordinates( start );
259  fprintf( workFile, "%g %g m ", pos_dev.x, pos_dev.y );
260  for( int ii = StAngle + delta; ii < EndAngle; ii += delta )
261  {
262  end.x = centre.x + KiROUND( cosdecideg( radius, -ii ) );
263  end.y = centre.y + KiROUND( sindecideg( radius, -ii ) );
264  pos_dev = userToDeviceCoordinates( end );
265  fprintf( workFile, "%g %g l ", pos_dev.x, pos_dev.y );
266  }
267 
268  end.x = centre.x + KiROUND( cosdecideg( radius, -EndAngle ) );
269  end.y = centre.y + KiROUND( sindecideg( radius, -EndAngle ) );
270  pos_dev = userToDeviceCoordinates( end );
271  fprintf( workFile, "%g %g l ", pos_dev.x, pos_dev.y );
272 
273  // The arc is drawn... if not filled we stroke it, otherwise we finish
274  // closing the pie at the center
275  if( fill == NO_FILL )
276  {
277  fputs( "S\n", workFile );
278  }
279  else
280  {
281  pos_dev = userToDeviceCoordinates( centre );
282  fprintf( workFile, "%g %g l b\n", pos_dev.x, pos_dev.y );
283  }
284 }
285 
286 
290 void PDF_PLOTTER::PlotPoly( const std::vector< wxPoint >& aCornerList,
291  FILL_T aFill, int aWidth, void * aData )
292 {
293  wxASSERT( workFile );
294  if( aCornerList.size() <= 1 )
295  return;
296 
297  SetCurrentLineWidth( aWidth );
298 
299  DPOINT pos = userToDeviceCoordinates( aCornerList[0] );
300  fprintf( workFile, "%g %g m\n", pos.x, pos.y );
301 
302  for( unsigned ii = 1; ii < aCornerList.size(); ii++ )
303  {
304  pos = userToDeviceCoordinates( aCornerList[ii] );
305  fprintf( workFile, "%g %g l\n", pos.x, pos.y );
306  }
307 
308  // Close path and stroke(/fill)
309  fprintf( workFile, "%c\n", aFill == NO_FILL ? 'S' : 'b' );
310 }
311 
312 
313 void PDF_PLOTTER::PenTo( const wxPoint& pos, char plume )
314 {
315  wxASSERT( workFile );
316  if( plume == 'Z' )
317  {
318  if( penState != 'Z' )
319  {
320  fputs( "S\n", workFile );
321  penState = 'Z';
322  penLastpos.x = -1;
323  penLastpos.y = -1;
324  }
325  return;
326  }
327 
328  if( penState != plume || pos != penLastpos )
329  {
330  DPOINT pos_dev = userToDeviceCoordinates( pos );
331  fprintf( workFile, "%g %g %c\n",
332  pos_dev.x, pos_dev.y,
333  ( plume=='D' ) ? 'l' : 'm' );
334  }
335  penState = plume;
336  penLastpos = pos;
337 }
338 
342 void PDF_PLOTTER::PlotImage( const wxImage & aImage, const wxPoint& aPos,
343  double aScaleFactor )
344 {
345  wxASSERT( workFile );
346  wxSize pix_size( aImage.GetWidth(), aImage.GetHeight() );
347 
348  // Requested size (in IUs)
349  DPOINT drawsize( aScaleFactor * pix_size.x,
350  aScaleFactor * pix_size.y );
351 
352  // calculate the bitmap start position
353  wxPoint start( aPos.x - drawsize.x / 2,
354  aPos.y + drawsize.y / 2);
355 
356  DPOINT dev_start = userToDeviceCoordinates( start );
357 
358  /* PDF has an uhm... simplified coordinate system handling. There is
359  *one* operator to do everything (the PS concat equivalent). At least
360  they kept the matrix stack to save restore environments. Also images
361  are always emitted at the origin with a size of 1x1 user units.
362  What we need to do is:
363  1) save the CTM end establish the new one
364  2) plot the image
365  3) restore the CTM
366  4) profit
367  */
368  fprintf( workFile, "q %g 0 0 %g %g %g cm\n", // Step 1
369  userToDeviceSize( drawsize.x ),
370  userToDeviceSize( drawsize.y ),
371  dev_start.x, dev_start.y );
372 
373  /* An inline image is a cross between a dictionary and a stream.
374  A real ugly construct (compared with the elegance of the PDF
375  format). Also it accepts some 'abbreviations', which is stupid
376  since the content stream is usually compressed anyway... */
377  fprintf( workFile,
378  "BI\n"
379  " /BPC 8\n"
380  " /CS %s\n"
381  " /W %d\n"
382  " /H %d\n"
383  "ID\n", colorMode ? "/RGB" : "/G", pix_size.x, pix_size.y );
384 
385  /* Here comes the stream (in binary!). I *could* have hex or ascii84
386  encoded it, but who cares? I'll go through zlib anyway */
387  for( int y = 0; y < pix_size.y; y++ )
388  {
389  for( int x = 0; x < pix_size.x; x++ )
390  {
391  unsigned char r = aImage.GetRed( x, y ) & 0xFF;
392  unsigned char g = aImage.GetGreen( x, y ) & 0xFF;
393  unsigned char b = aImage.GetBlue( x, y ) & 0xFF;
394 
395  // PDF inline images don't support alpha, so premultiply against white background
396  if( aImage.HasAlpha() )
397  {
398  unsigned char alpha = aImage.GetAlpha( x, y ) & 0xFF;
399 
400  if( alpha < 0xFF )
401  {
402  float a = 1.0 - ( (float) alpha / 255.0 );
403  r = ( int )( r + ( a * 0xFF ) ) & 0xFF;
404  g = ( int )( g + ( a * 0xFF ) ) & 0xFF;
405  b = ( int )( b + ( a * 0xFF ) ) & 0xFF;
406  }
407  }
408 
409  if( aImage.HasMask() )
410  {
411  if( r == aImage.GetMaskRed() && g == aImage.GetMaskGreen() && b == aImage.GetMaskBlue() )
412  {
413  r = 0xFF;
414  g = 0xFF;
415  b = 0xFF;
416  }
417  }
418 
419  // As usual these days, stdio buffering has to suffeeeeerrrr
420  if( colorMode )
421  {
422  putc( r, workFile );
423  putc( g, workFile );
424  putc( b, workFile );
425  }
426  else
427  {
428  // Greyscale conversion (CIE 1931)
429  unsigned char grey = KiROUND( r * 0.2126 + g * 0.7152 + b * 0.0722 );
430  putc( grey, workFile );
431  }
432  }
433  }
434 
435  fputs( "EI Q\n", workFile ); // Finish step 2 and do step 3
436 }
437 
438 
445 {
446  xrefTable.push_back( 0 );
447  return xrefTable.size() - 1;
448 }
449 
450 
456 {
457  wxASSERT( outputFile );
458  wxASSERT( !workFile );
459 
460  if( handle < 0)
461  handle = allocPdfObject();
462 
463  xrefTable[handle] = ftell( outputFile );
464  fprintf( outputFile, "%d 0 obj\n", handle );
465  return handle;
466 }
467 
468 
473 {
474  wxASSERT( outputFile );
475  wxASSERT( !workFile );
476  fputs( "endobj\n", outputFile );
477 }
478 
479 
487 {
488  wxASSERT( outputFile );
489  wxASSERT( !workFile );
490  handle = startPdfObject( handle );
491 
492  // This is guaranteed to be handle+1 but needs to be allocated since
493  // you could allocate more object during stream preparation
495  fprintf( outputFile,
496  "<< /Length %d 0 R /Filter /FlateDecode >>\n" // Length is deferred
497  "stream\n", handle + 1 );
498 
499  // Open a temporary file to accumulate the stream
500  workFilename = filename + wxT(".tmp");
501  workFile = wxFopen( workFilename, wxT( "w+b" ));
502  wxASSERT( workFile );
503  return handle;
504 }
505 
506 
511 {
512  wxASSERT( workFile );
513 
514  long stream_len = ftell( workFile );
515 
516  if( stream_len < 0 )
517  {
518  wxASSERT( false );
519  return;
520  }
521 
522  // Rewind the file, read in the page stream and DEFLATE it
523  fseek( workFile, 0, SEEK_SET );
524  unsigned char *inbuf = new unsigned char[stream_len];
525 
526  int rc = fread( inbuf, 1, stream_len, workFile );
527  wxASSERT( rc == stream_len );
528  (void) rc;
529 
530  // We are done with the temporary file, junk it
531  fclose( workFile );
532  workFile = 0;
533  ::wxRemoveFile( workFilename );
534 
535  // NULL means memos owns the memory, but provide a hint on optimum size needed.
536  wxMemoryOutputStream memos( NULL, std::max( 2000l, stream_len ) ) ;
537 
538  {
539  /* Somewhat standard parameters to compress in DEFLATE. The PDF spec is
540  * misleading, it says it wants a DEFLATE stream but it really want a ZLIB
541  * stream! (a DEFLATE stream would be generated with -15 instead of 15)
542  * rc = deflateInit2( &zstrm, Z_BEST_COMPRESSION, Z_DEFLATED, 15,
543  * 8, Z_DEFAULT_STRATEGY );
544  */
545 
546  wxZlibOutputStream zos( memos, wxZ_BEST_COMPRESSION, wxZLIB_ZLIB );
547 
548  zos.Write( inbuf, stream_len );
549 
550  delete[] inbuf;
551 
552  } // flush the zip stream using zos destructor
553 
554  wxStreamBuffer* sb = memos.GetOutputStreamBuffer();
555 
556  unsigned out_count = sb->Tell();
557 
558  fwrite( sb->GetBufferStart(), 1, out_count, outputFile );
559 
560  fputs( "endstream\n", outputFile );
561  closePdfObject();
562 
563  // Writing the deferred length as an indirect object
565  fprintf( outputFile, "%u\n", out_count );
566  closePdfObject();
567 }
568 
573 {
574  wxASSERT( outputFile );
575  wxASSERT( !workFile );
576 
577  // Compute the paper size in IUs
579  paperSize.x *= 10.0 / iuPerDeviceUnit;
580  paperSize.y *= 10.0 / iuPerDeviceUnit;
581 
582  // Open the content stream; the page object will go later
584 
585  /* Now, until ClosePage *everything* must be wrote in workFile, to be
586  compressed later in closePdfStream */
587 
588  // Default graphic settings (coordinate system, default color and line style)
589  fprintf( workFile,
590  "%g 0 0 %g 0 0 cm 1 J 1 j 0 0 0 rg 0 0 0 RG %g w\n",
591  0.0072 * plotScaleAdjX, 0.0072 * plotScaleAdjY,
593 }
594 
599 {
600  wxASSERT( workFile );
601 
602  // Close the page stream (and compress it)
603  closePdfStream();
604 
605  // Emit the page object and put it in the page list for later
606  pageHandles.push_back( startPdfObject() );
607 
608  /* Page size is in 1/72 of inch (default user space units)
609  Works like the bbox in postscript but there is no need for
610  swapping the sizes, since PDF doesn't require a portrait page.
611  We use the MediaBox but PDF has lots of other less used boxes
612  to use */
613 
614  const double BIGPTsPERMIL = 0.072;
615  wxSize psPaperSize = pageInfo.GetSizeMils();
616 
617  fprintf( outputFile,
618  "<<\n"
619  "/Type /Page\n"
620  "/Parent %d 0 R\n"
621  "/Resources <<\n"
622  " /ProcSet [/PDF /Text /ImageC /ImageB]\n"
623  " /Font %d 0 R >>\n"
624  "/MediaBox [0 0 %d %d]\n"
625  "/Contents %d 0 R\n"
626  ">>\n",
629  int( ceil( psPaperSize.x * BIGPTsPERMIL ) ),
630  int( ceil( psPaperSize.y * BIGPTsPERMIL ) ),
632  closePdfObject();
633 
634  // Mark the page stream as idle
635  pageStreamHandle = 0;
636 }
637 
644 {
645  wxASSERT( outputFile );
646 
647  // First things first: the customary null object
648  xrefTable.clear();
649  xrefTable.push_back( 0 );
650 
651  /* The header (that's easy!). The second line is binary junk required
652  to make the file binary from the beginning (the important thing is
653  that they must have the bit 7 set) */
654  fputs( "%PDF-1.5\n%\200\201\202\203\n", outputFile );
655 
656  /* Allocate an entry for the page tree root, it will go in every page
657  parent entry */
659 
660  /* In the same way, the font resource dictionary is used by every page
661  (it *could* be inherited via the Pages tree */
663 
664  /* Now, the PDF is read from the end, (more or less)... so we start
665  with the page stream for page 1. Other more important stuff is written
666  at the end */
667  StartPage();
668  return true;
669 }
670 
671 
673 {
674  wxASSERT( outputFile );
675 
676  // Close the current page (often the only one)
677  ClosePage();
678 
679  /* We need to declare the resources we're using (fonts in particular)
680  The useful standard one is the Helvetica family. Adding external fonts
681  is *very* involved! */
682  struct {
683  const char *psname;
684  const char *rsname;
685  int font_handle;
686  } fontdefs[4] = {
687  { "/Helvetica", "/KicadFont", 0 },
688  { "/Helvetica-Oblique", "/KicadFontI", 0 },
689  { "/Helvetica-Bold", "/KicadFontB", 0 },
690  { "/Helvetica-BoldOblique", "/KicadFontBI", 0 }
691  };
692 
693  /* Declare the font resources. Since they're builtin fonts, no descriptors (yay!)
694  We'll need metrics anyway to do any alignment (these are in the shared with
695  the postscript engine) */
696  for( int i = 0; i < 4; i++ )
697  {
698  fontdefs[i].font_handle = startPdfObject();
699  fprintf( outputFile,
700  "<< /BaseFont %s\n"
701  " /Type /Font\n"
702  " /Subtype /Type1\n"
703 
704  /* Adobe is so Mac-based that the nearest thing to Latin1 is
705  the Windows ANSI encoding! */
706  " /Encoding /WinAnsiEncoding\n"
707  ">>\n",
708  fontdefs[i].psname );
709  closePdfObject();
710  }
711 
712  // Named font dictionary (was allocated, now we emit it)
714  fputs( "<<\n", outputFile );
715  for( int i = 0; i < 4; i++ )
716  {
717  fprintf( outputFile, " %s %d 0 R\n",
718  fontdefs[i].rsname, fontdefs[i].font_handle );
719  }
720  fputs( ">>\n", outputFile );
721  closePdfObject();
722 
723  /* The page tree: it's a B-tree but luckily we only have few pages!
724  So we use just an array... The handle was allocated at the beginning,
725  now we instantiate the corresponding object */
727  fputs( "<<\n"
728  "/Type /Pages\n"
729  "/Kids [\n", outputFile );
730 
731  for( unsigned i = 0; i < pageHandles.size(); i++ )
732  fprintf( outputFile, "%d 0 R\n", pageHandles[i] );
733 
734  fprintf( outputFile,
735  "]\n"
736  "/Count %ld\n"
737  ">>\n", (long) pageHandles.size() );
738  closePdfObject();
739 
740 
741  // The info dictionary
742  int infoDictHandle = startPdfObject();
743  char date_buf[250];
744  time_t ltime = time( NULL );
745  strftime( date_buf, 250, "D:%Y%m%d%H%M%S",
746  localtime( &ltime ) );
747 
748  if( title.IsEmpty() )
749  {
750  // Windows uses '\' and other platforms ue '/' as sepatator
751  title = filename.AfterLast('\\');
752  title = title.AfterLast('/');
753  }
754 
755  fprintf( outputFile,
756  "<<\n"
757  "/Producer (KiCAD PDF)\n"
758  "/CreationDate (%s)\n"
759  "/Creator (%s)\n"
760  "/Title (%s)\n"
761  "/Trapped false\n",
762  date_buf,
763  TO_UTF8( creator ),
764  TO_UTF8( title ) );
765 
766  fputs( ">>\n", outputFile );
767  closePdfObject();
768 
769  // The catalog, at last
770  int catalogHandle = startPdfObject();
771  fprintf( outputFile,
772  "<<\n"
773  "/Type /Catalog\n"
774  "/Pages %d 0 R\n"
775  "/Version /1.5\n"
776  "/PageMode /UseNone\n"
777  "/PageLayout /SinglePage\n"
778  ">>\n", pageTreeHandle );
779  closePdfObject();
780 
781  /* Emit the xref table (format is crucial to the byte, each entry must
782  be 20 bytes long, and object zero must be done in that way). Also
783  the offset must be kept along for the trailer */
784  long xref_start = ftell( outputFile );
785  fprintf( outputFile,
786  "xref\n"
787  "0 %ld\n"
788  "0000000000 65535 f \n", (long) xrefTable.size() );
789  for( unsigned i = 1; i < xrefTable.size(); i++ )
790  {
791  fprintf( outputFile, "%010ld 00000 n \n", xrefTable[i] );
792  }
793 
794  // Done the xref, go for the trailer
795  fprintf( outputFile,
796  "trailer\n"
797  "<< /Size %lu /Root %d 0 R /Info %d 0 R >>\n"
798  "startxref\n"
799  "%ld\n" // The offset we saved before
800  "%%%%EOF\n",
801  (unsigned long) xrefTable.size(), catalogHandle, infoDictHandle, xref_start );
802 
803  fclose( outputFile );
804  outputFile = NULL;
805 
806  return true;
807 }
808 
809 void PDF_PLOTTER::Text( const wxPoint& aPos,
810  const COLOR4D aColor,
811  const wxString& aText,
812  double aOrient,
813  const wxSize& aSize,
814  enum EDA_TEXT_HJUSTIFY_T aH_justify,
815  enum EDA_TEXT_VJUSTIFY_T aV_justify,
816  int aWidth,
817  bool aItalic,
818  bool aBold,
819  bool aMultilineAllowed,
820  void* aData )
821 {
822  // PDF files do not like 0 sized texts which create broken files.
823  if( aSize.x == 0 || aSize.y == 0 )
824  return;
825 
826  // Fix me: see how to use PDF text mode for multiline texts
827  if( aMultilineAllowed && !aText.Contains( wxT( "\n" ) ) )
828  aMultilineAllowed = false; // the text has only one line.
829 
830  // Emit native PDF text (if requested)
831  // Currently: is not supported, because only our stroke font is alloxed: disable it
832  // However, shadowed texts (searchable texts) works reasonably well because
833  // pixel accurate precision is not requested, so we add searchable texts
834  // behind our stroked font texts
835  bool use_native_font = false;
836  // render_mode 0 shows the text, render_mode 3 is invisible
837  int render_mode = use_native_font ? 0 : 3;
838 
839  const char *fontname = aItalic ? (aBold ? "/KicadFontBI" : "/KicadFontI")
840  : (aBold ? "/KicadFontB" : "/KicadFont");
841 
842  // Compute the copious transformation parameters of the Curent Transform Matrix
843  double ctm_a, ctm_b, ctm_c, ctm_d, ctm_e, ctm_f;
844  double wideningFactor, heightFactor;
845 
846  computeTextParameters( aPos, aText, aOrient, aSize, m_plotMirror, aH_justify,
847  aV_justify, aWidth, aItalic, aBold,
848  &wideningFactor, &ctm_a, &ctm_b, &ctm_c,
849  &ctm_d, &ctm_e, &ctm_f, &heightFactor );
850 
851  SetColor( aColor );
852  SetCurrentLineWidth( aWidth, aData );
853 
854  /* We use the full CTM instead of the text matrix because the same
855  coordinate system will be used for the overlining. Also the %f
856  for the trig part of the matrix to avoid %g going in exponential
857  format (which is not supported)
858  render_mode 0 shows the text, render_mode 3 is invisible */
859  fprintf( workFile, "q %f %f %f %f %g %g cm BT %s %g Tf %d Tr %g Tz ",
860  ctm_a, ctm_b, ctm_c, ctm_d, ctm_e, ctm_f,
861  fontname, heightFactor, render_mode,
862  wideningFactor * 100 );
863 
864  // The text must be escaped correctly
866  fputs( " Tj ET\n", workFile );
867 
868  // We are in text coordinates, plot the overbars, if we're not doing phantom text
869  if( use_native_font )
870  {
871  std::vector<int> pos_pairs;
872  postscriptOverlinePositions( aText, aSize.x, aItalic, aBold, &pos_pairs );
873  int overbar_y = KiROUND( aSize.y * 1.1 );
874  for( unsigned i = 0; i < pos_pairs.size(); i += 2)
875  {
876  /* This is a nontrivial situation: we are *not* in the user
877  coordinate system, so the userToDeviceCoordinates function
878  can't be used! Strange as it may seem, the userToDeviceSize
879  is the right function to use here... */
880  DPOINT dev_from = userToDeviceSize( wxSize( pos_pairs[i], overbar_y ) );
881  DPOINT dev_to = userToDeviceSize( wxSize( pos_pairs[i + 1], overbar_y ) );
882  fprintf( workFile, "%g %g m %g %g l ",
883  dev_from.x, dev_from.y, dev_to.x, dev_to.y );
884  }
885  }
886 
887  // Stroke and restore the CTM
888  fputs( "S Q\n", workFile );
889 
890  // Plot the stroked text (if requested)
891  if( !use_native_font )
892  {
893  PLOTTER::Text( aPos, aColor, aText, aOrient, aSize, aH_justify, aV_justify,
894  aWidth, aItalic, aBold, aMultilineAllowed );
895  }
896 }
897 
double GetDotMarkLenIU() const
Definition: plotter.cpp:139
void closePdfStream()
Finish the current PDF stream (writes the deferred length, too)
EDA_TEXT_HJUSTIFY_T
Definition: eda_text.h:44
virtual bool EndPlot() override
virtual void StartPage()
Starts a new page in the PDF document.
int pageTreeHandle
Definition: plotter.h:924
virtual void PenTo(const wxPoint &pos, char plume) override
moveto/lineto primitive, moves the 'pen' to the specified direction
virtual void Text(const wxPoint &aPos, const COLOR4D aColor, const wxString &aText, double aOrient, const wxSize &aSize, enum EDA_TEXT_HJUSTIFY_T aH_justify, enum EDA_TEXT_VJUSTIFY_T aV_justify, int aWidth, bool aItalic, bool aBold, bool aMultilineAllowed=false, void *aData=NULL) override
Draws text with the plotter.
std::vector< int > pageHandles
Font resource dictionary.
Definition: plotter.h:926
virtual void SetDash(PLOT_DASH_TYPE dashed) override
PDF supports dashed lines.
bool colorMode
Definition: plotter.h:587
char penState
Current pen state: 'U', 'D' or 'Z' (see PenTo)
Definition: plotter.h:592
double m_IUsPerDecimil
Definition: plotter.h:569
wxPoint plotOffset
Plot offset (in IUs)
Definition: plotter.h:575
wxPoint penLastpos
Last pen positions; set to -1,-1 when the pen is at rest.
Definition: plotter.h:594
PAGE_INFO pageInfo
Definition: plotter.h:598
This file contains miscellaneous commonly used macros and functions.
virtual void Text(const wxPoint &aPos, const COLOR4D aColor, const wxString &aText, double aOrient, const wxSize &aSize, enum EDA_TEXT_HJUSTIFY_T aH_justify, enum EDA_TEXT_VJUSTIFY_T aV_justify, int aWidth, bool aItalic, bool aBold, bool aMultilineAllowed=false, void *aData=NULL)
Draws text with the plotter.
Definition: gr_text.cpp:232
wxString workFilename
Handle to the deferred stream length.
Definition: plotter.h:929
virtual void PlotPoly(const std::vector< wxPoint > &aCornerList, FILL_T aFill, int aWidth=USE_DEFAULT_LINE_WIDTH, void *aData=NULL) override
Polygon plotting for PDF.
double GetDashGapLenIU() const
Definition: plotter.cpp:151
#define TO_UTF8(wxstring)
Macro TO_UTF8 converts a wxString to a UTF8 encoded C string for all wxWidgets build modes.
Definition: macros.h:48
virtual void ClosePage()
Close the current page in the PDF document (and emit its compressed stream)
int streamLengthHandle
Handle of the page content object.
Definition: plotter.h:928
bool m_plotMirror
X axis orientation (SVG) and plot mirrored (only for PS, PDF HPGL and SVG)
Definition: plotter.h:579
#define NULL
virtual void SetDefaultLineWidth(int width) override
Set the default line width.
Definition: PS_plotter.cpp:53
virtual void Arc(const wxPoint &centre, double StAngle, double EndAngle, int rayon, FILL_T fill, int width=USE_DEFAULT_LINE_WIDTH) override
The PDF engine can't directly plot arcs, it uses the base emulation.
double plotScaleAdjY
Definition: plotter.h:780
int startPdfStream(int handle=-1)
Starts a PDF stream (for the page).
PAGE_INFO describes the page size and margins of a paper page on which to eventually print or plot.
Definition: page_info.h:54
int startPdfObject(int handle=-1)
Open a new PDF object and returns the handle if the parameter is -1.
virtual void SetViewport(const wxPoint &aOffset, double aIusPerDecimil, double aScale, bool aMirror) override
Set the plot offset and scaling for the current plot.
Definition: PDF_plotter.cpp:70
virtual void SetColor(COLOR4D color) override
The SetColor implementation is split with the subclasses: The PSLIKE computes the rgb values,...
Definition: PS_plotter.cpp:60
Base window classes and related definitions.
double plotScale
Plot scale - chosen by the user (even implicitly with 'fit in a4')
Definition: plotter.h:563
const wxSize & GetSizeMils() const
Definition: page_info.h:142
FILE * workFile
Definition: plotter.h:930
virtual DPOINT userToDeviceSize(const wxSize &size)
Modifies size according to the plotter scale factors (wxSize version, returns a DPOINT)
Definition: plotter.cpp:124
void closePdfObject()
Close the current PDF object.
PLOT_DASH_TYPE
Enum for choosing dashed line type.
Definition: plotter.h:86
EDA_TEXT_VJUSTIFY_T
Definition: eda_text.h:51
wxString title
Definition: plotter.h:597
virtual DPOINT userToDeviceCoordinates(const wxPoint &aCoordinate)
Modifies coordinates according to the orientation, scale factor, and offsets trace.
Definition: plotter.cpp:99
virtual void Rect(const wxPoint &p1, const wxPoint &p2, FILL_T fill, int width=USE_DEFAULT_LINE_WIDTH) override
Rectangles in PDF.
int fontResDictHandle
Handle to the root of the page tree object.
Definition: plotter.h:925
double cosdecideg(double r, double a)
Circle generation utility: computes r * cos(a) Where a is in decidegrees, not in radians.
Definition: trigo.h:365
double sindecideg(double r, double a)
Circle generation utility: computes r * sin(a) Where a is in decidegrees, not in radians.
Definition: trigo.h:356
void fputsPostscriptString(FILE *fout, const wxString &txt)
Write on a stream a string escaped for postscript/PDF.
Definition: PS_plotter.cpp:314
virtual void emitSetRGBColor(double r, double g, double b) override
PDF supports colors fully.
see class PGM_BASE
std::vector< long > xrefTable
Temporary file to costruct the stream before zipping.
Definition: plotter.h:931
int currentPenWidth
Definition: plotter.h:590
int defaultPenWidth
true to generate a negative image (PS mode mainly)
Definition: plotter.h:589
double GetDashMarkLenIU() const
Definition: plotter.cpp:145
virtual void Circle(const wxPoint &pos, int diametre, FILL_T fill, int width=USE_DEFAULT_LINE_WIDTH) override
Circle drawing for PDF.
double plotScaleAdjX
Fine user scale adjust ( = 1.0 if no correction)
Definition: plotter.h:780
FILE * outputFile
true if the Y axis is top to bottom (SVG)
Definition: plotter.h:584
constexpr ret_type KiROUND(fp_type v)
Round a floating point number to an integer using "round halfway cases away from zero".
Definition: util.h:61
The common library.
FILL_T
Enum FILL_T is the set of fill types used in plotting or drawing enclosed areas.
Definition: base_struct.h:42
void postscriptOverlinePositions(const wxString &aText, int aXSize, bool aItalic, bool aBold, std::vector< int > *pos_pairs)
Computes the x coordinates for the overlining in a string of text.
Definition: PS_plotter.cpp:382
virtual bool OpenFile(const wxString &aFullFilename) override
Open or create the plot file aFullFilename.
Definition: PDF_plotter.cpp:50
void computeTextParameters(const wxPoint &aPos, const wxString &aText, int aOrient, const wxSize &aSize, bool aMirror, enum EDA_TEXT_HJUSTIFY_T aH_justify, enum EDA_TEXT_VJUSTIFY_T aV_justify, int aWidth, bool aItalic, bool aBold, double *wideningFactor, double *ctm_a, double *ctm_b, double *ctm_c, double *ctm_d, double *ctm_e, double *ctm_f, double *heightFactor)
This is the core for postscript/PDF text alignment It computes the transformation matrix to generate ...
Definition: PS_plotter.cpp:435
virtual void SetPageSettings(const PAGE_INFO &aPageSettings) override
PDF can have multiple pages, so SetPageSettings can be called with the outputFile open (but not insid...
Definition: PDF_plotter.cpp:65
virtual bool StartPlot() override
The PDF engine supports multiple pages; the first one is opened 'for free' the following are to be cl...
double iuPerDeviceUnit
Device scale (from IUs to plotter device units - usually decimils)
Definition: plotter.h:572
wxString filename
Definition: plotter.h:596
int allocPdfObject()
Allocate a new handle in the table of the PDF object.
int pageStreamHandle
Handles to the page objects.
Definition: plotter.h:927
wxString creator
Definition: plotter.h:595
wxSize paperSize
Paper size in IU - not in mils.
Definition: plotter.h:600
virtual void SetCurrentLineWidth(int width, void *aData=NULL) override
Pen width setting for PDF.
Definition: PDF_plotter.cpp:96
COLOR4D is the color representation with 4 components: red, green, blue, alpha.
Definition: color4d.h:39
virtual void PlotImage(const wxImage &aImage, const wxPoint &aPos, double aScaleFactor) override
PDF images are handles as inline, not XObject streams...