KiCad PCB EDA Suite
Loading...
Searching...
No Matches
PDF_plotter.cpp
Go to the documentation of this file.
1/*
2 * This program source code file is part of KiCad, a free EDA CAD application.
3 *
4 * Copyright (C) 1992-2012 Lorenzo Marcantonio, [email protected]
5 * Copyright The KiCad Developers, see AUTHORS.txt for contributors.
6 *
7 * This program is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation; either version 2
10 * of the License, or (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
19 */
20
21#include <algorithm>
22#include <iterator>
23#include <cstdio> // snprintf
24#include <stack>
25#include <ranges>
26#include <vector>
27
28#include <wx/filename.h>
29#include <wx/mstream.h>
30#include <wx/zstream.h>
31#include <wx/wfstream.h>
32#include <wx/datstrm.h>
33#include <wx/tokenzr.h>
34
35#include <advanced_config.h>
36#include <common.h> // ResolveUriByEnvVars
37#include <eda_text.h> // for IsGotoPageHref
38#include <font/font.h>
39#include <gr_text.h>
40#include <core/ignore.h>
41#include <macros.h>
42#include <trace_helpers.h>
43#include <trigo.h>
44#include <string_utils.h>
45#include <core/utf8.h>
46#include <markup_parser.h>
47#include <fmt/format.h>
48#include <fmt/chrono.h>
49#include <fmt/ranges.h>
50
55#include <geometry/shape_rect.h>
57
58#include "callback_gal.h"
59
60
62
63#define GLM_ENABLE_EXPERIMENTAL //for older glm to enable euler angles
64#include <glm/glm.hpp>
65#include <glm/gtx/euler_angles.hpp>
66
67
68std::string PDF_PLOTTER::encodeStringForPlotter( const wxString& aText )
69{
70 // returns a string compatible with PDF string convention from a unicode string.
71 // if the initial text is only ASCII7, return the text between ( and ) for a good readability
72 // if the initial text contains non ASCII7, return the text between < and > encoded using
73 // UTF-16 BE (big-endian).
74 std::string result;
75
76 // Is aText only ASCII7 ?
77 bool is_ascii7 = true;
78
79 for( size_t ii = 0; ii < aText.Len(); ii++ )
80 {
81 if( aText[ii] >= 0x7F )
82 {
83 is_ascii7 = false;
84 break;
85 }
86 }
87
88 if( is_ascii7 )
89 {
90 result = '(';
91
92 for( size_t ii = 0; ii < aText.Len(); ii++ )
93 {
94 unsigned int code = aText[ii];
95
96 if( code == '(' || code == ')' || code == '\\' )
97 {
98 // These characters must be escaped.
99 result += '\\';
100 result += static_cast<char>( code );
101 }
102 else if( code < 0x20 )
103 {
104 // Control characters (inc. null) are not illegal in principle,
105 // but we use octal escapes for them to avoid confusing parsers.
106 result += fmt::format( "\\{:03o}", code );
107 }
108 else
109 {
110 result += static_cast<char>( code );
111 }
112 }
113
114 result += ')';
115 }
116 else
117 {
118 // UTF-16BE text string with BOM.
119 result = "<FEFF";
120
121 for( size_t ii = 0; ii < aText.Len(); ii++ )
122 {
123 unsigned int code = aText[ii];
124 result += FormatPdfUtf16Hex( static_cast<uint32_t>( code ) );
125 }
126
127 result += '>';
128 }
129
130 return result;
131}
132
133
134std::string PDF_PLOTTER::encodeDoubleForPlotter( double aValue ) const
135{
136 std::string buf = fmt::format( "{:g}", aValue );
137
138 // PDF syntax does not allow exponent notation (PostScript does). fmt's {:g} can emit it and
139 // can't be configured to force non-exponent output, so fall back to fixed when needed.
140 if( buf.find( 'e' ) != std::string::npos || buf.find( 'E' ) != std::string::npos )
141 buf = fmt::format( "{:.10f}", aValue );
142
143 if( buf.find( '.' ) != std::string::npos )
144 {
145 // Trim trailing zeros from fixed output while keeping at least one digit.
146 while( buf.size() > 1 && buf.back() == '0' )
147 buf.pop_back();
148
149 // Remove a dangling decimal point if we stripped all fractional digits.
150 if( !buf.empty() && buf.back() == '.' )
151 buf.pop_back();
152 }
153
154 // Avoid emitting "-0" for tiny negative values that round to zero.
155 if( buf == "-0" )
156 buf = "0";
157
158 return buf;
159}
160
161
162std::string PDF_PLOTTER::encodeByteString( const std::string& aBytes )
163{
164 std::string result;
165 result.reserve( aBytes.size() * 4 + 2 );
166 result.push_back( '(' );
167
168 for( unsigned char byte : aBytes )
169 {
170 if( byte == '(' || byte == ')' || byte == '\\' )
171 {
172 result.push_back( '\\' );
173 result.push_back( static_cast<char>( byte ) );
174 }
175 else if( byte < 32 || byte > 126 )
176 {
177 fmt::format_to( std::back_inserter( result ), "\\{:03o}", byte );
178 }
179 else
180 {
181 result.push_back( static_cast<char>( byte ) );
182 }
183 }
184
185 result.push_back( ')' );
186 return result;
187}
188
189
190bool PDF_PLOTTER::OpenFile( const wxString& aFullFilename )
191{
192 m_filename = aFullFilename;
193
194 wxASSERT( !m_outputFile );
195
196 // Open the PDF file in binary mode
197 m_outputFile = wxFopen( m_filename, wxT( "wb" ) );
198
199 if( m_outputFile == nullptr )
200 return false ;
201
202 return true;
203}
204
205
206void PDF_PLOTTER::SetViewport( const VECTOR2I& aOffset, double aIusPerDecimil, double aScale, bool aMirror )
207{
208 m_plotMirror = aMirror;
209 m_plotOffset = aOffset;
210 m_plotScale = aScale;
211 m_IUsPerDecimil = aIusPerDecimil;
212
213 // The CTM is set to 1 user unit per decimal
214 m_iuPerDeviceUnit = 1.0 / aIusPerDecimil;
215
216 /* The paper size in this engine is handled page by page
217 Look in the StartPage function */
218}
219
220
221void PDF_PLOTTER::SetCurrentLineWidth( int aWidth, void* aData )
222{
223 wxASSERT( m_workFile );
224
225 if( aWidth == DO_NOT_SET_LINE_WIDTH )
226 return;
227 else if( aWidth == USE_DEFAULT_LINE_WIDTH )
228 aWidth = m_renderSettings->GetDefaultPenWidth();
229
230 if( aWidth == 0 )
231 aWidth = 1;
232
233 wxASSERT_MSG( aWidth > 0, "Plotter called to set negative pen width" );
234
235 if( aWidth != m_currentPenWidth )
236 fmt::println( m_workFile, "{} w", encodeDoubleForPlotter( userToDeviceSize( aWidth ) ) );
237
238 m_currentPenWidth = aWidth;
239}
240
241
243{
244 auto [it, inserted] = m_alphaToExtGStateHandles.try_emplace( aAlpha );
245
246 if( inserted )
247 it->second = allocPdfObject();
248
249 return it->second;
250}
251
252
253void PDF_PLOTTER::emitSetRGBColor( double r, double g, double b, double a )
254{
255 wxASSERT( m_workFile );
256
257 fmt::println( m_workFile, "{} {} {} rg {} {} {} RG",
260
261 // PDF sets opacity through the graphics state
262 // It is 'sticky' and remains in effect until changed by another graphics state operator
263 // So change it if it differs from the current alpha value
264 if( a != m_currentAlpha )
265 {
266 const int extGStateHandle = getExtGStateHandleForAlpha( a );
267
268 // Apply that ExtGState to this context.
269 fmt::println( m_workFile, "/GS{} gs", extGStateHandle );
270
271 m_currentAlpha = a;
272 }
273}
274
275
276void PDF_PLOTTER::SetDash( int aLineWidth, LINE_STYLE aLineStyle )
277{
278 wxASSERT( m_workFile );
279
280 std::vector<int> pattern;
281
282 switch( aLineStyle )
283 {
284 case LINE_STYLE::DASH:
285 pattern = { (int) GetDashMarkLenIU( aLineWidth ), (int) GetDashGapLenIU( aLineWidth ) };
286 break;
287
288 case LINE_STYLE::DOT:
289 pattern = { (int) GetDotMarkLenIU( aLineWidth ), (int) GetDashGapLenIU( aLineWidth ) };
290 break;
291
293 pattern = { (int) GetDashMarkLenIU( aLineWidth ), (int) GetDashGapLenIU( aLineWidth ),
294 (int) GetDotMarkLenIU( aLineWidth ), (int) GetDashGapLenIU( aLineWidth ) };
295 break;
296
298 pattern = { (int) GetDashMarkLenIU( aLineWidth ), (int) GetDashGapLenIU( aLineWidth ),
299 (int) GetDotMarkLenIU( aLineWidth ), (int) GetDashGapLenIU( aLineWidth ),
300 (int) GetDotMarkLenIU( aLineWidth ), (int) GetDashGapLenIU( aLineWidth ) };
301 break;
302
303 default:
304 break;
305 }
306
307 // A PDF dash array whose elements sum to zero is illegal and makes strict viewers
308 // (Adobe Acrobat, Evince) abort rendering of the remaining page content. This happens
309 // when a dashed item is plotted with a zero pen width, e.g. a border-less filled shape
310 // whose stroke is dotted. Fall back to a solid line in that case.
311 bool allZero = std::all_of( pattern.begin(), pattern.end(), []( int v ) { return v == 0; } );
312
313 if( pattern.empty() || allZero )
314 {
315 fmt::println( m_workFile, "[] 0 d" );
316 return;
317 }
318
319 fmt::println( m_workFile, "[{}] 0 d", fmt::join( pattern, " " ) );
320}
321
322
323void PDF_PLOTTER::Rect( const VECTOR2I& p1, const VECTOR2I& p2, FILL_T fill, int width, int aCornerRadius )
324{
325 wxASSERT( m_workFile );
326
327 if( fill == FILL_T::NO_FILL && width == 0 )
328 return;
329
330 SetCurrentLineWidth( width );
331
332 if( aCornerRadius > 0 )
333 {
334 BOX2I box( p1, VECTOR2I( p2.x - p1.x, p2.y - p1.y ) );
335 box.Normalize();
336 SHAPE_RECT rect( box );
337 rect.SetRadius( aCornerRadius );
338 PlotPoly( rect.Outline(), fill, width, nullptr );
339 return;
340 }
341
342 VECTOR2I size = p2 - p1;
343
344 if( size.x == 0 && size.y == 0 )
345 {
346 // Can't draw zero-sized rectangles
347 MoveTo( VECTOR2I( p1.x, p1.y ) );
348 FinishTo( VECTOR2I( p1.x, p1.y ) );
349
350 return;
351 }
352
353 if( std::min( std::abs( size.x ), std::abs( size.y ) ) < width )
354 {
355 // Too thick stroked rectangles are buggy, draw as polygon
356 std::vector<VECTOR2I> cornerList;
357
358 cornerList.emplace_back( p1.x, p1.y );
359 cornerList.emplace_back( p2.x, p1.y );
360 cornerList.emplace_back( p2.x, p2.y );
361 cornerList.emplace_back( p1.x, p2.y );
362 cornerList.emplace_back( p1.x, p1.y );
363
364 PlotPoly( cornerList, fill, width, nullptr );
365
366 return;
367 }
368
369 VECTOR2D p1_dev = userToDeviceCoordinates( p1 );
370 VECTOR2D p2_dev = userToDeviceCoordinates( p2 );
371
372 char paintOp;
373
374 if( fill == FILL_T::NO_FILL )
375 paintOp = 'S';
376 else
377 paintOp = width > 0 ? 'B' : 'f';
378
379 fmt::println( m_workFile, "{} {} {} {} re {}",
380 encodeDoubleForPlotter( p1_dev.x ),
381 encodeDoubleForPlotter( p1_dev.y ),
382 encodeDoubleForPlotter( p2_dev.x - p1_dev.x ),
383 encodeDoubleForPlotter( p2_dev.y - p1_dev.y ),
384 paintOp );
385}
386
387
388void PDF_PLOTTER::Circle( const VECTOR2I& pos, int diametre, FILL_T aFill, int width )
389{
390 wxASSERT( m_workFile );
391
392 if( aFill == FILL_T::NO_FILL && width == 0 )
393 return;
394
395 SetCurrentLineWidth( width );
396
397 VECTOR2D pos_dev = userToDeviceCoordinates( pos );
398 const int effectiveWidth = GetCurrentLineWidth();
399 double radius = userToDeviceSize( diametre / 2.0 );
400
401 char paintOp = aFill == FILL_T::NO_FILL ? 's' : ( width == 0 ? 'f' : 'b' );
402
403 // If diameter is less than width, switch to filled mode
404 if( aFill == FILL_T::NO_FILL && diametre < effectiveWidth )
405 {
406 radius = userToDeviceSize( ( diametre / 2.0 ) + ( effectiveWidth / 2.0 ) );
407 paintOp = 'f';
408 }
409
410 /* OK. Here's a trick. PDF doesn't support circles or circular angles, that's
411 a fact. You'll have to do with cubic beziers. These *can't* represent
412 circular arcs (NURBS can, beziers don't). But there is a widely known
413 approximation which is really good
414 */
415
416 double magic = radius * 0.551784; // You don't want to know where this come from
417
418 // This is the convex hull for the bezier approximated circle
419 fmt::println( m_workFile,
420 "{} {} m "
421 "{} {} {} {} {} {} c "
422 "{} {} {} {} {} {} c "
423 "{} {} {} {} {} {} c "
424 "{} {} {} {} {} {} c {}",
425 encodeDoubleForPlotter( pos_dev.x - radius ), encodeDoubleForPlotter( pos_dev.y ),
426
427 encodeDoubleForPlotter( pos_dev.x - radius ), encodeDoubleForPlotter( pos_dev.y + magic ),
428 encodeDoubleForPlotter( pos_dev.x - magic ), encodeDoubleForPlotter( pos_dev.y + radius ),
429 encodeDoubleForPlotter( pos_dev.x ), encodeDoubleForPlotter( pos_dev.y + radius ),
430
431 encodeDoubleForPlotter( pos_dev.x + magic ), encodeDoubleForPlotter( pos_dev.y + radius ),
432 encodeDoubleForPlotter( pos_dev.x + radius ), encodeDoubleForPlotter( pos_dev.y + magic ),
433 encodeDoubleForPlotter( pos_dev.x + radius ), encodeDoubleForPlotter( pos_dev.y ),
434
435 encodeDoubleForPlotter( pos_dev.x + radius ), encodeDoubleForPlotter( pos_dev.y - magic ),
436 encodeDoubleForPlotter( pos_dev.x + magic ), encodeDoubleForPlotter( pos_dev.y - radius ),
437 encodeDoubleForPlotter( pos_dev.x ), encodeDoubleForPlotter( pos_dev.y - radius ),
438
439 encodeDoubleForPlotter( pos_dev.x - magic ), encodeDoubleForPlotter( pos_dev.y - radius ),
440 encodeDoubleForPlotter( pos_dev.x - radius ), encodeDoubleForPlotter( pos_dev.y - magic ),
441 encodeDoubleForPlotter( pos_dev.x - radius ), encodeDoubleForPlotter( pos_dev.y ),
442
443 paintOp );
444}
445
446
447std::vector<VECTOR2D> PDF_PLOTTER::arcPath( const VECTOR2D& aCenter, const EDA_ANGLE& aStartAngle,
448 const EDA_ANGLE& aAngle, double aRadius )
449{
450 std::vector<VECTOR2D> path;
451
452 /*
453 * Arcs are not so easily approximated by beziers (in the general case), so we approximate
454 * them in the old way
455 */
456 EDA_ANGLE startAngle = -aStartAngle;
457 EDA_ANGLE endAngle = startAngle - aAngle;
458 VECTOR2I start;
460 const EDA_ANGLE delta( 5, DEGREES_T ); // increment to draw circles
461
462 if( startAngle > endAngle )
463 std::swap( startAngle, endAngle );
464
465 // Usual trig arc plotting routine...
466 start.x = KiROUND( aCenter.x + aRadius * ( -startAngle ).Cos() );
467 start.y = KiROUND( aCenter.y + aRadius * ( -startAngle ).Sin() );
468 path.emplace_back( userToDeviceCoordinates( start ) );
469
470 for( EDA_ANGLE ii = startAngle + delta; ii < endAngle; ii += delta )
471 {
472 end.x = KiROUND( aCenter.x + aRadius * ( -ii ).Cos() );
473 end.y = KiROUND( aCenter.y + aRadius * ( -ii ).Sin() );
474 path.emplace_back( userToDeviceCoordinates( end ) );
475 }
476
477 end.x = KiROUND( aCenter.x + aRadius * ( -endAngle ).Cos() );
478 end.y = KiROUND( aCenter.y + aRadius * ( -endAngle ).Sin() );
479 path.emplace_back( userToDeviceCoordinates( end ) );
480
481 return path;
482}
483
484
485void PDF_PLOTTER::Arc( const VECTOR2D& aCenter, const EDA_ANGLE& aStartAngle,
486 const EDA_ANGLE& aAngle, double aRadius, FILL_T aFill, int aWidth )
487{
488 wxASSERT( m_workFile );
489
490 SetCurrentLineWidth( aWidth );
491
492 if( aRadius <= 0 )
493 {
495 return;
496 }
497
498 std::vector<VECTOR2D> path = arcPath( aCenter, aStartAngle, aAngle, aRadius );
499
500 if( path.size() >= 2 )
501 {
502 fmt::print( m_workFile, "{} {} m ",
504
505 for( int ii = 1; ii < (int) path.size(); ++ii )
506 {
507 fmt::print( m_workFile, "{} {} l ",
509 }
510 }
511
512 // The arc is drawn... if not filled we stroke it, otherwise we finish
513 // closing the pie at the center
514 if( aFill == FILL_T::NO_FILL )
515 {
516 fmt::println( m_workFile, "S" );
517 }
518 else
519 {
520 VECTOR2D pos_dev = userToDeviceCoordinates( aCenter );
521 fmt::println( m_workFile, "{} {} l b",
522 encodeDoubleForPlotter( pos_dev.x ), encodeDoubleForPlotter( pos_dev.y ) );
523 }
524}
525
526
527void PDF_PLOTTER::PlotPoly( const std::vector<VECTOR2I>& aCornerList, FILL_T aFill, int aWidth,
528 void* aData )
529{
530 wxASSERT( m_workFile );
531
532 if( aCornerList.size() <= 1 )
533 return;
534
535 if( aFill == FILL_T::NO_FILL && aWidth == 0 )
536 return;
537
538 SetCurrentLineWidth( aWidth );
539
540 VECTOR2D pos = userToDeviceCoordinates( aCornerList[0] );
541 fmt::print( m_workFile, "{:f} {:f} m ", pos.x, pos.y );
542
543 for( unsigned ii = 1; ii < aCornerList.size(); ii++ )
544 {
545 pos = userToDeviceCoordinates( aCornerList[ii] );
546 fmt::print( m_workFile, "{:f} {:f} l ", pos.x, pos.y );
547 }
548
549 // Close path and stroke and/or fill
550 if( aFill == FILL_T::NO_FILL )
551 fmt::println( m_workFile, "S" );
552 else if( aWidth == 0 )
553 fmt::println( m_workFile, "h f" );
554 else
555 fmt::println( m_workFile, "b" );
556}
557
558
559void PDF_PLOTTER::PlotPoly( const SHAPE_LINE_CHAIN& aLineChain, FILL_T aFill, int aWidth, void* aData )
560{
561 if( aFill == FILL_T::NO_FILL && aWidth == 0 )
562 return;
563
564 SetCurrentLineWidth( aWidth );
565
566 std::set<size_t> handledArcs;
567 std::vector<VECTOR2D> path;
568
569 for( int ii = 0; ii < aLineChain.SegmentCount(); ++ii )
570 {
571 if( aLineChain.IsArcSegment( ii ) )
572 {
573 size_t arcIndex = aLineChain.ArcIndex( ii );
574
575 if( !handledArcs.contains( arcIndex ) )
576 {
577 handledArcs.insert( arcIndex );
578 const SHAPE_ARC& arc( aLineChain.Arc( arcIndex ) );
579 std::vector<VECTOR2D> arc_path = arcPath( arc.GetCenter(), arc.GetStartAngle(),
580 arc.GetCentralAngle(), arc.GetRadius() );
581
582 for( const VECTOR2D& pt : std::ranges::reverse_view( arc_path ) )
583 path.emplace_back( pt );
584 }
585 }
586 else
587 {
588 const SEG& seg( aLineChain.Segment( ii ) );
589 path.emplace_back( userToDeviceCoordinates( seg.A ) );
590 path.emplace_back( userToDeviceCoordinates( seg.B ) );
591 }
592 }
593
594 if( path.size() <= 1 )
595 return;
596
597 fmt::print( m_workFile, "{} {} m ",
599
600 for( int ii = 1; ii < (int) path.size(); ++ii )
601 {
602 fmt::print( m_workFile, "{} {} l ",
604 }
605
606 // Close path and stroke and/or fill
607 if( aFill == FILL_T::NO_FILL )
608 fmt::println( m_workFile, "S" );
609 else if( aWidth == 0 )
610 fmt::println( m_workFile, "h f" );
611 else
612 fmt::println( m_workFile, "b" );
613}
614
615
616void PDF_PLOTTER::PenTo( const VECTOR2I& pos, char plume )
617{
618 wxASSERT( m_workFile );
619
620 if( plume == 'Z' )
621 {
622 if( m_penState != 'Z' )
623 {
624 fmt::println( m_workFile, "S" );
625 m_penState = 'Z';
626 m_penLastpos.x = -1;
627 m_penLastpos.y = -1;
628 }
629
630 return;
631 }
632
633 if( m_penState != plume || pos != m_penLastpos )
634 {
635 VECTOR2D pos_dev = userToDeviceCoordinates( pos );
636 fmt::println( m_workFile, "{:f} {:f} {}",
637 pos_dev.x,
638 pos_dev.y,
639 plume == 'D' ? 'l' : 'm' );
640 }
641
642 m_penState = plume;
643 m_penLastpos = pos;
644}
645
646
647void PDF_PLOTTER::PlotImage( const wxImage& aImage, const VECTOR2I& aPos, double aScaleFactor, double aAlpha )
648{
649 wxASSERT( m_workFile );
650 VECTOR2I pix_size( aImage.GetWidth(), aImage.GetHeight() );
651
652 // Requested size (in IUs)
653 VECTOR2D drawsize( aScaleFactor * pix_size.x, aScaleFactor * pix_size.y );
654
655 // calculate the bitmap start position
656 VECTOR2I start( aPos.x - drawsize.x / 2, aPos.y + drawsize.y / 2 );
657 VECTOR2D dev_start = userToDeviceCoordinates( start );
658
659 // Deduplicate images
660 auto findHandleForImage =
661 [&]( const wxImage& aCurrImage ) -> int
662 {
663 for( const auto& [imgHandle, image] : m_imageHandles )
664 {
665 if( image.IsSameAs( aCurrImage ) )
666 return imgHandle;
667
668 if( image.GetWidth() != aCurrImage.GetWidth() )
669 continue;
670
671 if( image.GetHeight() != aCurrImage.GetHeight() )
672 continue;
673
674 if( image.GetType() != aCurrImage.GetType() )
675 continue;
676
677 if( image.HasAlpha() != aCurrImage.HasAlpha() )
678 continue;
679
680 if( image.HasMask() != aCurrImage.HasMask()
681 || image.GetMaskRed() != aCurrImage.GetMaskRed()
682 || image.GetMaskGreen() != aCurrImage.GetMaskGreen()
683 || image.GetMaskBlue() != aCurrImage.GetMaskBlue() )
684 {
685 continue;
686 }
687
688 int pixCount = image.GetWidth() * image.GetHeight();
689
690 if( memcmp( image.GetData(), aCurrImage.GetData(), pixCount * 3 ) != 0 )
691 continue;
692
693 if( image.HasAlpha() && memcmp( image.GetAlpha(), aCurrImage.GetAlpha(), pixCount ) != 0 )
694 continue;
695
696 return imgHandle;
697 }
698
699 return -1;
700 };
701
702 int imgHandle = findHandleForImage( aImage );
703
704 if( imgHandle == -1 )
705 {
706 imgHandle = allocPdfObject();
707 m_imageHandles.emplace( imgHandle, aImage );
708 }
709
710 /* PDF has an uhm... simplified coordinate system handling. There is
711 *one* operator to do everything (the PS concat equivalent). At least
712 they kept the matrix stack to save restore environments. Also images
713 are always emitted at the origin with a size of 1x1 user units.
714 What we need to do is:
715 1) save the CTM end establish the new one
716 2) plot the image
717 3) restore the CTM
718 4) profit
719 */
720 fmt::println( m_workFile, "q {} 0 0 {} {} {} cm", // Step 1
723 encodeDoubleForPlotter( dev_start.x ),
724 encodeDoubleForPlotter( dev_start.y ) );
725
726 // Apply any global alpha setting for this image (on top of the image's own alpha)
727 if( m_currentAlpha != aAlpha )
728 fmt::println( m_workFile, "/GS{} gs", getExtGStateHandleForAlpha( aAlpha ) );
729
730 fmt::println( m_workFile, "/Im{} Do", imgHandle );
731 fmt::println( m_workFile, "Q" );
732}
733
734
736{
737 return m_xrefTable.Allocate();
738}
739
740
742{
743 wxASSERT( m_outputFile );
744 wxASSERT( !m_workFile );
745
746 if( !m_xrefTable.IsValid( aHandle ) )
747 {
748 wxASSERT_MSG( aHandle < 0, "PDF object handle given was not previously allocated" );
749 aHandle = allocPdfObject();
750 }
751
752 m_xrefTable.SetOffset( aHandle, ftell( m_outputFile ) );
753 fmt::println( m_outputFile, "{} 0 obj", aHandle );
754 return aHandle;
755}
756
757
759{
760 wxASSERT( m_outputFile );
761 wxASSERT( !m_workFile );
762 fmt::println( m_outputFile, "endobj" );
763}
764
765
767{
768 wxASSERT( m_outputFile );
769 wxASSERT( !m_workFile );
770 int handle = startPdfObject( aHandle );
771
772 // This is guaranteed to be handle+1 but needs to be allocated since
773 // you could allocate more object during stream preparation
775
776 if( ADVANCED_CFG::GetCfg().m_DebugPDFWriter )
777 {
778 fmt::print( m_outputFile, "<< /Length {} 0 R >>\nstream\n",
780 }
781 else
782 {
783 fmt::print( m_outputFile, "<< /Length {} 0 R /Filter /FlateDecode >>\nstream\n",
785 }
786
787 // Open a temporary file to accumulate the stream
788 m_workFilename = wxFileName::CreateTempFileName( "" );
789 m_workFile = wxFopen( m_workFilename, wxT( "w+b" ) );
790 wxASSERT( m_workFile );
791 return handle;
792}
793
794
796{
797 wxASSERT( m_workFile );
798
799 long stream_len = ftell( m_workFile );
800
801 if( stream_len < 0 )
802 {
803 wxASSERT( false );
804 return;
805 }
806
807 // Rewind the file, read in the page stream and DEFLATE it
808 fseek( m_workFile, 0, SEEK_SET );
809 unsigned char *inbuf = new unsigned char[stream_len];
810
811 int rc = fread( inbuf, 1, stream_len, m_workFile );
812 wxASSERT( rc == stream_len );
813 ignore_unused( rc );
814
815 // We are done with the temporary file, junk it
816 fclose( m_workFile );
817 m_workFile = nullptr;
818 ::wxRemoveFile( m_workFilename );
819
820 unsigned out_count;
821
822 if( ADVANCED_CFG::GetCfg().m_DebugPDFWriter )
823 {
824 out_count = stream_len;
825 fwrite( inbuf, out_count, 1, m_outputFile );
826 }
827 else
828 {
829 // NULL means memos owns the memory, but provide a hint on optimum size needed.
830 wxMemoryOutputStream memos( nullptr, std::max( 2000l, stream_len ) ) ;
831
832 {
833 /* Somewhat standard parameters to compress in DEFLATE. The PDF spec is
834 * misleading, it says it wants a DEFLATE stream but it really want a ZLIB
835 * stream! (a DEFLATE stream would be generated with -15 instead of 15)
836 * rc = deflateInit2( &zstrm, Z_BEST_COMPRESSION, Z_DEFLATED, 15,
837 * 8, Z_DEFAULT_STRATEGY );
838 */
839
840 wxZlibOutputStream zos( memos, wxZ_BEST_COMPRESSION, wxZLIB_ZLIB );
841
842 zos.Write( inbuf, stream_len );
843 } // flush the zip stream using zos destructor
844
845 wxStreamBuffer* sb = memos.GetOutputStreamBuffer();
846
847 out_count = sb->Tell();
848 fwrite( sb->GetBufferStart(), 1, out_count, m_outputFile );
849 }
850
851 delete[] inbuf;
852 fmt::print( m_outputFile, "\nendstream\n" );
854
855 // Writing the deferred length as an indirect object
857 fmt::println( m_outputFile, "{}", out_count );
859}
860
861
862void PDF_PLOTTER::StartPage( const wxString& aPageNumber, const wxString& aPageName,
863 const wxString& aParentPageNumber, const wxString& aParentPageName )
864{
865 wxASSERT( m_outputFile );
866 wxASSERT( !m_workFile );
867
868 m_pageNumbers.push_back( aPageNumber );
869 m_pageName = aPageName.IsEmpty() ? wxString::Format( _( "Page %s" ),
870 aPageNumber )
871 : wxString::Format( _( "%s (Page %s)" ),
872 aPageName,
873 aPageNumber );
874 m_parentPageName = aParentPageName.IsEmpty() ? wxString::Format( _( "Page %s" ),
875 aParentPageNumber )
876 : wxString::Format( _( "%s (Page %s)" ),
877 aParentPageName,
878 aParentPageNumber );
879
880 // Compute the paper size in IUs
881 m_paperSize = m_pageInfo.GetSizeMils();
882 m_paperSize.x *= 10.0 / m_iuPerDeviceUnit;
883 m_paperSize.y *= 10.0 / m_iuPerDeviceUnit;
884
885 // Set m_currentPenWidth to a unused value to ensure the pen width
886 // will be initialized to a the right value in pdf file by the first item to plot
888
889 // Each page content stream starts with a default graphics state
890 m_currentAlpha = 1.0;
891
892 if( !m_3dExportMode )
893 {
894 // Open the content stream; the page object will go later
896
897 /* Now, until ClosePage *everything* must be wrote in workFile, to be
898 compressed later in closePdfStream */
899
900 // Default graphic settings (coordinate system, default color and line style)
901 fmt::println( m_workFile,
902 "{} 0 0 {} 0 0 cm 1 J 1 j 0 0 0 rg 0 0 0 RG {} w",
905 encodeDoubleForPlotter( userToDeviceSize( m_renderSettings->GetDefaultPenWidth() ) ) );
906 }
907}
908
909
910void WriteImageStream( const wxImage& aImage, wxDataOutputStream& aOut, const wxColor& bg, bool colorMode )
911{
912 int w = aImage.GetWidth();
913 int h = aImage.GetHeight();
914
915 for( int y = 0; y < h; y++ )
916 {
917 for( int x = 0; x < w; x++ )
918 {
919 unsigned char r = aImage.GetRed( x, y ) & 0xFF;
920 unsigned char g = aImage.GetGreen( x, y ) & 0xFF;
921 unsigned char b = aImage.GetBlue( x, y ) & 0xFF;
922
923 if( aImage.HasMask() )
924 {
925 if( r == aImage.GetMaskRed() && g == aImage.GetMaskGreen() && b == aImage.GetMaskBlue() )
926 {
927 r = bg.Red();
928 g = bg.Green();
929 b = bg.Blue();
930 }
931 }
932
933 if( colorMode )
934 {
935 aOut.Write8( r );
936 aOut.Write8( g );
937 aOut.Write8( b );
938 }
939 else
940 {
941 // Greyscale conversion (CIE 1931)
942 unsigned char grey = KiROUND( r * 0.2126 + g * 0.7152 + b * 0.0722 );
943
944 aOut.Write8( grey );
945 }
946 }
947 }
948}
949
950
951void WriteImageSMaskStream( const wxImage& aImage, wxDataOutputStream& aOut )
952{
953 int w = aImage.GetWidth();
954 int h = aImage.GetHeight();
955
956 if( aImage.HasMask() )
957 {
958 for( int y = 0; y < h; y++ )
959 {
960 for( int x = 0; x < w; x++ )
961 {
962 unsigned char a = 255;
963 unsigned char r = aImage.GetRed( x, y );
964 unsigned char g = aImage.GetGreen( x, y );
965 unsigned char b = aImage.GetBlue( x, y );
966
967 if( r == aImage.GetMaskRed() && g == aImage.GetMaskGreen() && b == aImage.GetMaskBlue() )
968 a = 0;
969
970 aOut.Write8( a );
971 }
972 }
973 }
974 else if( aImage.HasAlpha() )
975 {
976 int size = w * h;
977 aOut.Write8( aImage.GetAlpha(), size );
978 }
979}
980
981
983{
984 // non 3d exports need this
985 if( m_pageStreamHandle != -1 )
986 {
987 wxASSERT( m_workFile );
988
989 // Close the page stream (and compress it)
991 }
992
993 // Page size is in 1/72 of inch (default user space units). Works like the bbox in postscript
994 // but there is no need for swapping the sizes, since PDF doesn't require a portrait page.
995 // We use the MediaBox but PDF has lots of other less-used boxes that could be used.
996 const double PTsPERMIL = 0.072;
997 VECTOR2D psPaperSize = VECTOR2D( m_pageInfo.GetSizeMils() ) * PTsPERMIL;
998
999 auto iuToPdfUserSpace =
1000 [&]( const VECTOR2I& aCoord ) -> VECTOR2D
1001 {
1002 VECTOR2D pos = ( aCoord - m_plotOffset ) * m_plotScale;
1003 pos *= PTsPERMIL / ( m_IUsPerDecimil * 10 );
1004
1005 // PDF y=0 is at bottom of page, invert coordinate
1006 VECTOR2D retval( pos.x, psPaperSize.y - pos.y );
1007
1008 // The pdf plot can be mirrored (from left to right). So mirror the
1009 // x coordinate if m_plotMirror is set
1010 if( m_plotMirror )
1011 {
1013 retval.x = ( psPaperSize.x - pos.x );
1014 else
1015 retval.y = pos.y;
1016 }
1017
1018 return retval;
1019 };
1020
1021 // Handle annotations (at the moment only "link" type objects)
1022 std::vector<int> annotHandles;
1023
1024 // Allocate all hyperlink objects for the page and calculate their position in user space
1025 // coordinates
1026 for( const std::pair<BOX2I, wxString>& linkPair : m_hyperlinksInPage )
1027 {
1028 const BOX2I& box = linkPair.first;
1029 const wxString& url = linkPair.second;
1030
1031 VECTOR2D bottomLeft = iuToPdfUserSpace( box.GetPosition() );
1032 VECTOR2D topRight = iuToPdfUserSpace( box.GetEnd() );
1033
1034 BOX2D userSpaceBox;
1035 userSpaceBox.SetOrigin( bottomLeft );
1036 userSpaceBox.SetEnd( topRight );
1037
1038 annotHandles.push_back( allocPdfObject() );
1039
1040 m_hyperlinkHandles.insert( { annotHandles.back(), { userSpaceBox, url } } );
1041 }
1042
1043 for( const std::pair<BOX2I, std::vector<wxString>>& menuPair : m_hyperlinkMenusInPage )
1044 {
1045 const BOX2I& box = menuPair.first;
1046 const std::vector<wxString>& urls = menuPair.second;
1047
1048 VECTOR2D bottomLeft = iuToPdfUserSpace( box.GetPosition() );
1049 VECTOR2D topRight = iuToPdfUserSpace( box.GetEnd() );
1050
1051 BOX2D userSpaceBox;
1052 userSpaceBox.SetOrigin( bottomLeft );
1053 userSpaceBox.SetEnd( topRight );
1054
1055 annotHandles.push_back( allocPdfObject() );
1056
1057 m_hyperlinkMenuHandles.insert( { annotHandles.back(), { userSpaceBox, urls } } );
1058 }
1059
1060 int annot3DHandle = -1;
1061
1062 if( m_3dExportMode )
1063 {
1064 annot3DHandle = allocPdfObject();
1065 annotHandles.push_back( annot3DHandle );
1066 }
1067
1068
1069 int annotArrayHandle = -1;
1070
1071 // If we have added any annotation links, create an array containing all the objects
1072 if( annotHandles.size() > 0 )
1073 {
1074 annotArrayHandle = startPdfObject();
1075 bool isFirst = true;
1076
1077 fmt::print( m_outputFile, "[" );
1078
1079 for( int handle : annotHandles )
1080 {
1081 if( isFirst )
1082 isFirst = false;
1083 else
1084 fmt::print( m_outputFile, " " );
1085
1086 fmt::print( m_outputFile, "{} 0 R", handle );
1087 }
1088
1089 fmt::println( m_outputFile, "]" );
1091 }
1092
1093 // Emit the page object and put it in the page list for later
1094 int pageHandle = startPdfObject();
1095 m_pageHandles.push_back( pageHandle );
1096
1097 fmt::print( m_outputFile,
1098 "<<\n"
1099 "/Type /Page\n"
1100 "/Parent {} 0 R\n"
1101 "/Resources <<\n"
1102 " /ProcSet [/PDF /Text /ImageC /ImageB]\n"
1103 " /Font {} 0 R\n"
1104 " /XObject {} 0 R\n"
1105 " /ExtGState {} 0 R >>\n"
1106 "/MediaBox [0 0 {} {}]\n",
1111 encodeDoubleForPlotter( psPaperSize.x ),
1112 encodeDoubleForPlotter( psPaperSize.y ) );
1113
1114 if( m_pageStreamHandle != -1 )
1115 fmt::print( m_outputFile, "/Contents {} 0 R\n", m_pageStreamHandle );
1116
1117 if( annotHandles.size() > 0 )
1118 fmt::print( m_outputFile, "/Annots {} 0 R", annotArrayHandle );
1119
1120 fmt::print( m_outputFile, ">>\n" );
1121
1123
1124 if( m_3dExportMode )
1125 {
1126 startPdfObject( annot3DHandle );
1127 fmt::print( m_outputFile,
1128 "<<\n"
1129 "/Type /Annot\n"
1130 "/Subtype /3D\n"
1131 "/Rect [0 0 {} {}]\n"
1132 "/NM (3D Annotation)\n"
1133 "/3DD {} 0 R\n"
1134 "/3DV 0\n"
1135 "/3DA<</A/PO/D/PC/TB true/NP true>>\n"
1136 "/3DI true\n"
1137 "/P {} 0 R\n"
1138 ">>\n",
1139 encodeDoubleForPlotter( psPaperSize.x ),
1140 encodeDoubleForPlotter( psPaperSize.y ),
1142 pageHandle );
1143
1145 }
1146
1147 // Mark the page stream as idle
1148 m_pageStreamHandle = -1;
1149
1150 int actionHandle = emitGoToAction( pageHandle );
1151 PDF_PLOTTER::OUTLINE_NODE* parent_node = m_outlineRoot.get();
1152
1153 if( !m_parentPageName.IsEmpty() )
1154 {
1155 // Search for the parent node iteratively through the entire tree
1156 std::stack<OUTLINE_NODE*> nodes;
1157 nodes.push( m_outlineRoot.get() );
1158
1159 while( !nodes.empty() )
1160 {
1161 OUTLINE_NODE* node = nodes.top();
1162 nodes.pop();
1163
1164 // Check if this node matches
1165 if( node->title == m_parentPageName )
1166 {
1167 parent_node = node;
1168 break;
1169 }
1170
1171 // Add all children to the stack
1172 for( OUTLINE_NODE* child : node->children )
1173 nodes.push( child );
1174 }
1175 }
1176
1177 OUTLINE_NODE* pageOutlineNode = addOutlineNode( parent_node, actionHandle, m_pageName );
1178
1179 // let's reorg the symbol bookmarks under a page handle
1180 // let's reorg the symbol bookmarks under a page handle
1181 for( const auto& [groupName, groupVector] : m_bookmarksInPage )
1182 {
1183 OUTLINE_NODE* groupOutlineNode = addOutlineNode( pageOutlineNode, actionHandle, groupName );
1184
1185 for( const std::pair<BOX2I, wxString>& bookmarkPair : groupVector )
1186 {
1187 const BOX2I& box = bookmarkPair.first;
1188 const wxString& ref = bookmarkPair.second;
1189
1190 VECTOR2I bottomLeft = iuToPdfUserSpace( box.GetPosition() );
1191 VECTOR2I topRight = iuToPdfUserSpace( box.GetEnd() );
1192
1193 actionHandle = emitGoToAction( pageHandle, bottomLeft, topRight );
1194
1195 addOutlineNode( groupOutlineNode, actionHandle, ref );
1196 }
1197
1198 std::sort( groupOutlineNode->children.begin(), groupOutlineNode->children.end(),
1199 []( const OUTLINE_NODE* a, const OUTLINE_NODE* b ) -> bool
1200 {
1201 return a->title < b->title;
1202 } );
1203 }
1204
1205 // Clean up
1206 m_hyperlinksInPage.clear();
1207 m_hyperlinkMenusInPage.clear();
1208 m_bookmarksInPage.clear();
1209}
1210
1211
1212bool PDF_PLOTTER::StartPlot( const wxString& aPageNumber )
1213{
1214 return StartPlot( aPageNumber, wxEmptyString );
1215}
1216
1217
1218bool PDF_PLOTTER::StartPlot( const wxString& aPageNumber, const wxString& aPageName )
1219{
1220 wxASSERT( m_outputFile );
1221
1222 // First things first: the customary null object
1223 m_pageHandles.clear();
1224 m_xrefTable.Reset();
1225 m_pageNumbers.clear();
1226 m_hyperlinksInPage.clear();
1227 m_hyperlinkMenusInPage.clear();
1228 m_hyperlinkHandles.clear();
1229 m_hyperlinkMenuHandles.clear();
1230 m_bookmarksInPage.clear();
1231 m_imageHandles.clear();
1234 m_usedBase14Fonts = false;
1235
1236 m_outlineRoot = std::make_unique<OUTLINE_NODE>();
1237
1238 if( !m_strokeFontManager )
1239 m_strokeFontManager = std::make_unique<PDF_STROKE_FONT_MANAGER>();
1240 else
1241 m_strokeFontManager->Reset();
1242
1244 m_outlineFontManager = std::make_unique<PDF_OUTLINE_FONT_MANAGER>();
1245 else
1246 m_outlineFontManager->Reset();
1247
1248 /* The header (that's easy!). The second line is binary junk required
1249 to make the file binary from the beginning (the important thing is
1250 that they must have the bit 7 set) */
1251 fmt::print( m_outputFile, "%PDF-1.5\n%\200\201\202\203\n" );
1252
1253 /* Allocate an entry for the page tree root, it will go in every page parent entry */
1255
1256 /* In the same way, the font resource dictionary is used by every page
1257 (it *could* be inherited via the Pages tree */
1259
1261
1263
1265
1266 /* Now, the PDF is read from the end, (more or less)... so we start
1267 with the page stream for page 1. Other more important stuff is written
1268 at the end */
1269 StartPage( aPageNumber, aPageName );
1270 return true;
1271}
1272
1273
1274int PDF_PLOTTER::emitGoToAction( int aPageHandle, const VECTOR2I& aBottomLeft, const VECTOR2I& aTopRight )
1275{
1276 int actionHandle = allocPdfObject();
1277 startPdfObject( actionHandle );
1278
1279 fmt::print( m_outputFile,
1280 "<</S /GoTo /D [{} 0 R /FitR {} {} {} {}]\n"
1281 ">>\n",
1282 aPageHandle,
1283 aBottomLeft.x,
1284 aBottomLeft.y,
1285 aTopRight.x,
1286 aTopRight.y );
1287
1289
1290 return actionHandle;
1291}
1292
1293
1294int PDF_PLOTTER::emitGoToAction( int aPageHandle )
1295{
1296 int actionHandle = allocPdfObject();
1297 startPdfObject( actionHandle );
1298
1299 fmt::println( m_outputFile,
1300 "<</S /GoTo /D [{} 0 R /Fit]\n"
1301 ">>",
1302 aPageHandle );
1303
1305
1306 return actionHandle;
1307}
1308
1309
1310void PDF_PLOTTER::emitOutlineNode( OUTLINE_NODE* node, int parentHandle, int nextNode, int prevNode )
1311{
1312 int nodeHandle = node->entryHandle;
1313 int prevHandle = -1;
1314 int nextHandle = -1;
1315
1316 for( std::vector<OUTLINE_NODE*>::iterator it = node->children.begin(); it != node->children.end(); it++ )
1317 {
1318 if( it >= node->children.end() - 1 )
1319 nextHandle = -1;
1320 else
1321 nextHandle = ( *( it + 1 ) )->entryHandle;
1322
1323 emitOutlineNode( *it, nodeHandle, nextHandle, prevHandle );
1324
1325 prevHandle = ( *it )->entryHandle;
1326 }
1327
1328 // -1 for parentHandle is the outline root itself which is handed elsewhere.
1329 if( parentHandle != -1 )
1330 {
1331 startPdfObject( nodeHandle );
1332
1333 fmt::print( m_outputFile,
1334 "<<\n"
1335 "/Title {}\n"
1336 "/Parent {} 0 R\n",
1338 parentHandle);
1339
1340 if( nextNode > 0 )
1341 fmt::println( m_outputFile, "/Next {} 0 R", nextNode );
1342
1343 if( prevNode > 0 )
1344 fmt::println( m_outputFile, "/Prev {} 0 R", prevNode );
1345
1346 if( node->children.size() > 0 )
1347 {
1348 int32_t count = -1 * static_cast<int32_t>( node->children.size() );
1349 fmt::println( m_outputFile, "/Count {}", count );
1350 fmt::println( m_outputFile, "/First {} 0 R", node->children.front()->entryHandle );
1351 fmt::println( m_outputFile, "/Last {} 0 R", node->children.back()->entryHandle );
1352 }
1353
1354 if( node->actionHandle != -1 )
1355 fmt::println( m_outputFile, "/A {} 0 R", node->actionHandle );
1356
1357 fmt::println( m_outputFile, ">>" );
1359 }
1360}
1361
1362
1364 const wxString& aTitle )
1365{
1366 OUTLINE_NODE *node = aParent->AddChild( aActionHandle, aTitle, allocPdfObject() );
1368
1369 return node;
1370}
1371
1372
1374{
1375 if( m_outlineRoot->children.size() > 0 )
1376 {
1377 // declare the outline object
1378 m_outlineRoot->entryHandle = allocPdfObject();
1379
1380 emitOutlineNode( m_outlineRoot.get(), -1, -1, -1 );
1381
1382 startPdfObject( m_outlineRoot->entryHandle );
1383
1384 fmt::print( m_outputFile,
1385 "<< /Type /Outlines\n"
1386 " /Count {}\n"
1387 " /First {} 0 R\n"
1388 " /Last {} 0 R\n"
1389 ">>\n",
1391 m_outlineRoot->children.front()->entryHandle,
1392 m_outlineRoot->children.back()->entryHandle
1393 );
1394
1396
1397 return m_outlineRoot->entryHandle;
1398 }
1399
1400 return -1;
1401}
1402
1403
1405{
1406 if( !m_strokeFontManager )
1407 return;
1408
1409 for( PDF_STROKE_FONT_SUBSET* subsetPtr : m_strokeFontManager->AllSubsets() )
1410 {
1411 PDF_STROKE_FONT_SUBSET& subset = *subsetPtr;
1412
1413 if( subset.GlyphCount() <= 1 )
1414 {
1415 subset.SetCharProcsHandle( -1 );
1416 subset.SetFontHandle( -1 );
1417 subset.SetToUnicodeHandle( -1 );
1418 continue;
1419 }
1420
1421 for( PDF_STROKE_FONT_SUBSET::GLYPH& glyph : subset.Glyphs() )
1422 {
1423 int charProcHandle = startPdfStream();
1424
1425 if( !glyph.m_stream.empty() )
1426 fmt::print( m_workFile, "{}\n", glyph.m_stream );
1427
1429 glyph.m_charProcHandle = charProcHandle;
1430 }
1431
1432 int charProcDictHandle = startPdfObject();
1433 fmt::println( m_outputFile, "<<" );
1434
1435 for( const PDF_STROKE_FONT_SUBSET::GLYPH& glyph : subset.Glyphs() )
1436 fmt::println( m_outputFile, " /{} {} 0 R", glyph.m_name, glyph.m_charProcHandle );
1437
1438 fmt::println( m_outputFile, ">>" );
1440 subset.SetCharProcsHandle( charProcDictHandle );
1441
1442 int toUnicodeHandle = startPdfStream();
1443 std::string cmap = subset.BuildToUnicodeCMap();
1444
1445 if( !cmap.empty() )
1446 fmt::print( m_workFile, "{}", cmap );
1447
1449 subset.SetToUnicodeHandle( toUnicodeHandle );
1450
1451 double fontMatrixScale = 1.0 / subset.UnitsPerEm();
1452 double minX = subset.FontBBoxMinX();
1453 double minY = subset.FontBBoxMinY();
1454 double maxX = subset.FontBBoxMaxX();
1455 double maxY = subset.FontBBoxMaxY();
1456
1457 int fontHandle = startPdfObject();
1458 fmt::print( m_outputFile,
1459 "<<\n/Type /Font\n/Subtype /Type3\n/Name {}\n/FontBBox [ {} {} {} {} ]\n",
1460 subset.ResourceName(),
1461 encodeDoubleForPlotter( minX ),
1462 encodeDoubleForPlotter( minY ),
1463 encodeDoubleForPlotter( maxX ),
1464 encodeDoubleForPlotter( maxY ) );
1465 fmt::print( m_outputFile,
1466 "/FontMatrix [ {} 0 0 {} 0 0 ]\n/CharProcs {} 0 R\n",
1467 encodeDoubleForPlotter( fontMatrixScale ),
1468 encodeDoubleForPlotter( fontMatrixScale ),
1469 subset.CharProcsHandle() );
1470 fmt::print( m_outputFile,
1471 "/Encoding << /Type /Encoding /Differences {} >>\n",
1472 subset.BuildDifferencesArray() );
1473 fmt::print( m_outputFile,
1474 "/FirstChar {}\n/LastChar {}\n/Widths {}\n",
1475 subset.FirstChar(),
1476 subset.LastChar(),
1477 subset.BuildWidthsArray() );
1478 fmt::print( m_outputFile,
1479 "/ToUnicode {} 0 R\n/Resources << /ProcSet [/PDF /Text] >>\n>>\n",
1480 subset.ToUnicodeHandle() );
1482 subset.SetFontHandle( fontHandle );
1483 }
1484}
1485
1486
1488{
1490 return;
1491
1492 for( PDF_OUTLINE_FONT_SUBSET* subsetPtr : m_outlineFontManager->AllSubsets() )
1493 {
1494 if( !subsetPtr || !subsetPtr->HasGlyphs() )
1495 continue;
1496
1497 const std::vector<uint8_t>& fontData = subsetPtr->FontFileData();
1498
1499 if( fontData.empty() )
1500 continue;
1501
1502 int fontFileHandle = startPdfStream();
1503 subsetPtr->SetFontFileHandle( fontFileHandle );
1504
1505 if( !fontData.empty() )
1506 fwrite( fontData.data(), fontData.size(), 1, m_workFile );
1507
1509
1510 std::string cidMap = subsetPtr->BuildCIDToGIDStream();
1511 int cidMapHandle = startPdfStream();
1512 subsetPtr->SetCIDMapHandle( cidMapHandle );
1513
1514 if( !cidMap.empty() )
1515 fwrite( cidMap.data(), cidMap.size(), 1, m_workFile );
1516
1518
1519 std::string toUnicode = subsetPtr->BuildToUnicodeCMap();
1520 int toUnicodeHandle = startPdfStream();
1521 subsetPtr->SetToUnicodeHandle( toUnicodeHandle );
1522
1523 if( !toUnicode.empty() )
1524 fmt::print( m_workFile, "{}", toUnicode );
1525
1527
1528 int descriptorHandle = startPdfObject();
1529 subsetPtr->SetFontDescriptorHandle( descriptorHandle );
1530
1531 fmt::print( m_outputFile,
1532 "<<\n/Type /FontDescriptor\n/FontName /{}\n/Flags {}\n/ItalicAngle {}\n/Ascent {}\n/Descent {}\n"
1533 "/CapHeight {}\n/StemV {}\n/FontBBox [ {} {} {} {} ]\n/FontFile2 {} 0 R\n>>\n",
1534 subsetPtr->BaseFontName(),
1535 subsetPtr->Flags(),
1536 encodeDoubleForPlotter( subsetPtr->ItalicAngle() ),
1537 encodeDoubleForPlotter( subsetPtr->Ascent() ),
1538 encodeDoubleForPlotter( subsetPtr->Descent() ),
1539 encodeDoubleForPlotter( subsetPtr->CapHeight() ),
1540 encodeDoubleForPlotter( subsetPtr->StemV() ),
1541 encodeDoubleForPlotter( subsetPtr->BBoxMinX() ),
1542 encodeDoubleForPlotter( subsetPtr->BBoxMinY() ),
1543 encodeDoubleForPlotter( subsetPtr->BBoxMaxX() ),
1544 encodeDoubleForPlotter( subsetPtr->BBoxMaxY() ),
1545 subsetPtr->FontFileHandle() );
1547
1548 int cidFontHandle = startPdfObject();
1549 subsetPtr->SetCIDFontHandle( cidFontHandle );
1550
1551 std::string widths = subsetPtr->BuildWidthsArray();
1552
1553 fmt::print( m_outputFile,
1554 "<<\n/Type /Font\n/Subtype /CIDFontType2\n/BaseFont /{}\n"
1555 "/CIDSystemInfo << /Registry (Adobe) /Ordering (Identity) /Supplement 0 >>\n"
1556 "/FontDescriptor {} 0 R\n/W {}\n/CIDToGIDMap {} 0 R\n>>\n",
1557 subsetPtr->BaseFontName(),
1558 subsetPtr->FontDescriptorHandle(),
1559 widths,
1560 subsetPtr->CIDMapHandle() );
1562
1563 int fontHandle = startPdfObject();
1564 subsetPtr->SetFontHandle( fontHandle );
1565
1566 fmt::print( m_outputFile,
1567 "<<\n/Type /Font\n/Subtype /Type0\n/BaseFont /{}\n/Encoding /Identity-H\n"
1568 "/DescendantFonts [ {} 0 R ]\n/ToUnicode {} 0 R\n>>\n",
1569 subsetPtr->BaseFontName(),
1570 subsetPtr->CIDFontHandle(),
1571 subsetPtr->ToUnicodeHandle() );
1573 }
1574}
1575
1576
1578{
1581
1582 // The non-embeddable font fallback writes Tf against these names, so they must be declared
1583 // or the invisible searchable layer is an undefined resource
1584 struct
1585 {
1586 const char* psname;
1587 const char* rsname;
1588 int handle;
1589 } base14[4] = {
1590 { "/Helvetica", "/KicadFont", 0 },
1591 { "/Helvetica-Oblique", "/KicadFontI", 0 },
1592 { "/Helvetica-Bold", "/KicadFontB", 0 },
1593 { "/Helvetica-BoldOblique", "/KicadFontBI", 0 }
1594 };
1595
1596 if( m_usedBase14Fonts )
1597 {
1598 for( auto& font : base14 )
1599 {
1600 font.handle = startPdfObject();
1601 fmt::println( m_outputFile,
1602 "<< /BaseFont {}\n"
1603 " /Type /Font\n"
1604 " /Subtype /Type1\n"
1605 " /Encoding /WinAnsiEncoding\n"
1606 ">>",
1607 font.psname );
1609 }
1610 }
1611
1613 fmt::println( m_outputFile, "<<" );
1614
1615 if( m_usedBase14Fonts )
1616 {
1617 for( const auto& font : base14 )
1618 fmt::println( m_outputFile, " {} {} 0 R", font.rsname, font.handle );
1619 }
1620
1622 {
1623 for( PDF_OUTLINE_FONT_SUBSET* subsetPtr : m_outlineFontManager->AllSubsets() )
1624 {
1625 if( subsetPtr && subsetPtr->FontHandle() >= 0 )
1626 fmt::println( m_outputFile, " {} {} 0 R", subsetPtr->ResourceName(), subsetPtr->FontHandle() );
1627 }
1628 }
1629
1631 {
1632 for( PDF_STROKE_FONT_SUBSET* subsetPtr : m_strokeFontManager->AllSubsets() )
1633 {
1634 const PDF_STROKE_FONT_SUBSET& subset = *subsetPtr;
1635
1636 if( subset.FontHandle() >= 0 )
1637 fmt::println( m_outputFile, " {} {} 0 R", subset.ResourceName(), subset.FontHandle() );
1638 }
1639 }
1640
1641 fmt::println( m_outputFile, ">>" );
1643
1644 // Named image dictionary (was allocated, now we emit it)
1646 fmt::println( m_outputFile, "<<\n" );
1647
1648 for( const auto& [imgHandle, image] : m_imageHandles )
1649 fmt::print( m_outputFile, " /Im{} {} 0 R\n", imgHandle, imgHandle );
1650
1651 fmt::println( m_outputFile, ">>" );
1653
1654 // Graphics state objects.
1655 // For now, we have only alpha-setting graphics state objects.
1656 // If we we had other types of graphics state objects, we would handle them here as well.
1657 // We re-use the handle as the resource name: handle 42 -> '/GS42'
1658 {
1659 // First, write out all the external graphics state objects one at a time
1660 for( const auto& [alpha, handle] : m_alphaToExtGStateHandles )
1661 {
1662 startPdfObject( handle );
1663 fmt::println( m_outputFile, "<< /Type /ExtGState /ca {} /CA {} >>", encodeDoubleForPlotter( alpha ),
1664 encodeDoubleForPlotter( alpha ) );
1666 }
1667
1668 // Now write out the external graphics state resource dictionary
1670 fmt::println( m_outputFile, "<<" );
1671
1672 for( const auto& [alpha, handle] : m_alphaToExtGStateHandles )
1673 fmt::println( m_outputFile, " /GS{} {} 0 R", handle, handle );
1674
1675 fmt::println( m_outputFile, ">>" );
1677 }
1678
1679 // Emit images with optional SMask for transparency
1680 for( const auto& [imgHandle, image] : m_imageHandles )
1681 {
1682 // Init wxFFile so wxFFileOutputStream won't close file in dtor.
1683 wxFFile outputFFile( m_outputFile );
1684
1685 // Image
1686 startPdfObject( imgHandle );
1687 int imgLenHandle = allocPdfObject();
1688 int smaskHandle = ( image.HasAlpha() || image.HasMask() ) ? allocPdfObject() : -1;
1689
1690 fmt::print( m_outputFile,
1691 "<<\n"
1692 "/Type /XObject\n"
1693 "/Subtype /Image\n"
1694 "/BitsPerComponent 8\n"
1695 "/ColorSpace {}\n"
1696 "/Width {}\n"
1697 "/Height {}\n"
1698 "/Filter /FlateDecode\n"
1699 "/Length {} 0 R\n", // Length is deferred
1700 m_colorMode ? "/DeviceRGB" : "/DeviceGray",
1701 image.GetWidth(),
1702 image.GetHeight(),
1703 imgLenHandle );
1704
1705 if( smaskHandle != -1 )
1706 fmt::println( m_outputFile, "/SMask {} 0 R", smaskHandle );
1707
1708 fmt::println( m_outputFile, ">>" );
1709 fmt::println( m_outputFile, "stream" );
1710
1711 long imgStreamStart = ftell( m_outputFile );
1712
1713 {
1714 wxFFileOutputStream ffos( outputFFile );
1715 wxZlibOutputStream zos( ffos, wxZ_BEST_COMPRESSION, wxZLIB_ZLIB );
1716 wxDataOutputStream dos( zos );
1717
1718 WriteImageStream( image, dos, m_renderSettings->GetBackgroundColor().ToColour(),
1719 m_colorMode );
1720 }
1721
1722 long imgStreamSize = ftell( m_outputFile ) - imgStreamStart;
1723
1724 fmt::print( m_outputFile, "\nendstream\n" );
1726
1727 startPdfObject( imgLenHandle );
1728 fmt::println( m_outputFile, "{}", imgStreamSize );
1730
1731 if( smaskHandle != -1 )
1732 {
1733 // SMask
1734 startPdfObject( smaskHandle );
1735 int smaskLenHandle = allocPdfObject();
1736
1737 fmt::print( m_outputFile,
1738 "<<\n"
1739 "/Type /XObject\n"
1740 "/Subtype /Image\n"
1741 "/BitsPerComponent 8\n"
1742 "/ColorSpace /DeviceGray\n"
1743 "/Width {}\n"
1744 "/Height {}\n"
1745 "/Length {} 0 R\n"
1746 "/Filter /FlateDecode\n"
1747 ">>\n", // Length is deferred
1748 image.GetWidth(),
1749 image.GetHeight(),
1750 smaskLenHandle );
1751
1752 fmt::println( m_outputFile, "stream" );
1753
1754 long smaskStreamStart = ftell( m_outputFile );
1755
1756 {
1757 wxFFileOutputStream ffos( outputFFile );
1758 wxZlibOutputStream zos( ffos, wxZ_BEST_COMPRESSION, wxZLIB_ZLIB );
1759 wxDataOutputStream dos( zos );
1760
1762 }
1763
1764 long smaskStreamSize = ftell( m_outputFile ) - smaskStreamStart;
1765
1766 fmt::print( m_outputFile, "\nendstream\n" );
1768
1769 startPdfObject( smaskLenHandle );
1770 fmt::println( m_outputFile, "{}", (unsigned) smaskStreamSize );
1772 }
1773
1774 outputFFile.Detach(); // Don't close it
1775 }
1776
1777 for( const auto& [ linkHandle, linkPair ] : m_hyperlinkHandles )
1778 {
1779 BOX2D box = linkPair.first;
1780 wxString url = linkPair.second;
1781
1782 startPdfObject( linkHandle );
1783
1784 fmt::print( m_outputFile,
1785 "<<\n"
1786 "/Type /Annot\n"
1787 "/Subtype /Link\n"
1788 "/Rect [{} {} {} {}]\n"
1789 "/Border [16 16 0]\n",
1793 encodeDoubleForPlotter( box.GetTop() ) );
1794
1795 wxString pageNumber;
1796 bool pageFound = false;
1797
1798 if( EDA_TEXT::IsGotoPageHref( url, &pageNumber ) )
1799 {
1800 for( size_t ii = 0; ii < m_pageNumbers.size(); ++ii )
1801 {
1802 if( m_pageNumbers[ii] == pageNumber )
1803 {
1804 fmt::print( m_outputFile,
1805 "/Dest [{} 0 R /FitB]\n"
1806 ">>\n",
1807 m_pageHandles[ii] );
1808
1809 pageFound = true;
1810 break;
1811 }
1812 }
1813
1814 if( !pageFound )
1815 {
1816 // destination page is not being plotted, assign the NOP action to the link
1817 fmt::print( m_outputFile,
1818 "/A << /Type /Action /S /NOP >>\n"
1819 ">>\n" );
1820 }
1821 }
1822 else
1823 {
1824 if( m_project )
1825 url = ResolveUriByEnvVars( url, m_project );
1826
1827 fmt::print( m_outputFile,
1828 "/A << /Type /Action /S /URI /URI {} >>\n"
1829 ">>\n",
1830 encodeStringForPlotter( url ) );
1831 }
1832
1834 }
1835
1836 for( const auto& [ menuHandle, menuPair ] : m_hyperlinkMenuHandles )
1837 {
1838 const BOX2D& box = menuPair.first;
1839 const std::vector<wxString>& urls = menuPair.second;
1840 wxString js = wxT( "ShM([\n" );
1841
1842 for( const wxString& url : urls )
1843 {
1844 if( url.StartsWith( "!" ) )
1845 {
1846 wxString property = url.AfterFirst( '!' );
1847
1848 if( property.Find( "http:" ) >= 0 )
1849 {
1850 wxString href = property.substr( property.Find( "http:" ) );
1851
1852 if( m_project )
1853 href = ResolveUriByEnvVars( href, m_project );
1854
1855 js += wxString::Format( wxT( "[\"%s\", \"%s\"],\n" ), EscapeString( property, CTX_JS_STR ),
1856 EscapeString( href, CTX_JS_STR ) );
1857 }
1858 else if( property.Find( "https:" ) >= 0 )
1859 {
1860 wxString href = property.substr( property.Find( "https:" ) );
1861
1862 if( m_project )
1863 href = ResolveUriByEnvVars( href, m_project );
1864
1865 js += wxString::Format( wxT( "[\"%s\", \"%s\"],\n" ), EscapeString( property, CTX_JS_STR ),
1866 EscapeString( href, CTX_JS_STR ) );
1867 }
1868 else if( property.Find( "file:" ) >= 0 )
1869 {
1870 wxString href = property.substr( property.Find( "file:" ) );
1871
1872 if( m_project )
1873 href = ResolveUriByEnvVars( href, m_project );
1874
1875 href = NormalizeFileUri( href );
1876 wxString displayText = property.substr( 0, property.Find( "file:" ) ) + href;
1877
1878 js += wxString::Format( wxT( "[\"%s\", \"%s\"],\n" ), EscapeString( displayText, CTX_JS_STR ),
1879 EscapeString( href, CTX_JS_STR ) );
1880 }
1881 else
1882 {
1883 // Legacy fallback
1884 int eqPos = property.Find( wxS( " = " ) );
1885 wxString href;
1886 bool converted = false;
1887
1888 if( eqPos != wxNOT_FOUND )
1889 {
1890 href = property.Mid( eqPos + 3 );
1891
1892 if( m_project )
1893 href = ResolveUriByEnvVars( href, m_project );
1894
1895 if( href.StartsWith( wxS( "/" ) ) || href.StartsWith( wxS( "${" ) )
1896 || ( href.Length() >= 2 && wxIsalpha( href[0] ) && href[1] == ':' )
1897 || href.StartsWith( wxS( "\\\\" ) ) )
1898 {
1899 if( !href.StartsWith( wxS( "/" ) ) )
1900 {
1901 href.Replace( wxS( "\\" ), wxS( "/" ) );
1902
1903 if( href.StartsWith( wxS( "//" ) ) )
1904 href = wxS( "file:" ) + href;
1905 else
1906 href = wxS( "file:///" ) + href;
1907 }
1908 else
1909 {
1910 href = wxS( "file://" ) + href;
1911 }
1912
1913 href = NormalizeFileUri( href );
1914 converted = true;
1915 }
1916 }
1917
1918 if( converted )
1919 {
1920 js += wxString::Format( wxT( "[\"%s\", \"%s\"],\n" ),
1921 EscapeString( property, CTX_JS_STR ),
1922 EscapeString( href, CTX_JS_STR ) );
1923 }
1924 else
1925 {
1926 js += wxString::Format( wxT( "[\"%s\"],\n" ), EscapeString( property, CTX_JS_STR ) );
1927 }
1928 }
1929 }
1930 else if( url.StartsWith( "#" ) )
1931 {
1932 wxString pageNumber = url.AfterFirst( '#' );
1933
1934 for( size_t ii = 0; ii < m_pageNumbers.size(); ++ii )
1935 {
1936 if( m_pageNumbers[ii] == pageNumber )
1937 {
1938 wxString menuText = wxString::Format( _( "Show Page %s" ), pageNumber );
1939
1940 js += wxString::Format( wxT( "[\"%s\", \"#%d\"],\n" ),
1941 EscapeString( menuText, CTX_JS_STR ),
1942 static_cast<int>( ii ) );
1943 break;
1944 }
1945 }
1946 }
1947 else
1948 {
1949 wxString href = url;
1950
1951 if( m_project )
1952 href = ResolveUriByEnvVars( href, m_project );
1953
1954 // Convert bare file paths to file:// URIs (legacy support)
1955 if( !href.StartsWith( wxS( "http:" ) )
1956 && !href.StartsWith( wxS( "https:" ) )
1957 && !href.StartsWith( wxS( "file:" ) ) )
1958 {
1959 if( href.StartsWith( wxS( "/" ) ) || href.StartsWith( wxS( "${" ) ) )
1960 {
1961 href = wxS( "file://" ) + href;
1962 }
1963 else if( href.Length() >= 2 && wxIsalpha( href[0] ) && href[1] == ':' )
1964 {
1965 href.Replace( wxS( "\\" ), wxS( "/" ) );
1966 href = wxS( "file:///" ) + href;
1967 }
1968 else if( href.StartsWith( wxS( "\\\\" ) ) )
1969 {
1970 href.Replace( wxS( "\\" ), wxS( "/" ) );
1971 href = wxS( "file:" ) + href;
1972 }
1973 }
1974
1975 if( href.StartsWith( wxS( "file:" ) ) )
1976 href = NormalizeFileUri( href );
1977
1978 if( href.StartsWith( wxS( "http:" ) )
1979 || href.StartsWith( wxS( "https:" ) )
1980 || href.StartsWith( wxS( "file:" ) ) )
1981 {
1982 wxString menuText = wxString::Format( _( "Open %s" ), href );
1983
1984 js += wxString::Format( wxT( "[\"%s\", \"%s\"],\n" ),
1985 EscapeString( menuText, CTX_JS_STR ),
1986 EscapeString( href, CTX_JS_STR ) );
1987 }
1988 }
1989 }
1990
1991 js += wxT( "]);" );
1992
1993 startPdfObject( menuHandle );
1994
1995 fmt::print( m_outputFile,
1996 "<<\n"
1997 "/Type /Annot\n"
1998 "/Subtype /Link\n"
1999 "/Rect [{} {} {} {}]\n"
2000 "/Border [16 16 0]\n",
2004 encodeDoubleForPlotter( box.GetTop() ) );
2005
2006 fmt::print( m_outputFile,
2007 "/A << /Type /Action /S /JavaScript /JS {} >>\n"
2008 ">>\n",
2009 encodeStringForPlotter( js ) );
2010
2012 }
2013
2014 {
2016
2017 wxString js = R"JS(
2018function ShM(aEntries) {
2019 var aParams = [];
2020 for (var i = 0; i < aEntries.length; ++i) {
2021 aParams.push({
2022 cName: aEntries[i][0],
2023 cReturn: aEntries[i].length > 1 ? aEntries[i][1] : ''
2024 })
2025 }
2026
2027 var cChoice = app.popUpMenuEx.apply(app, aParams);
2028 if (cChoice == null || cChoice == '') return;
2029
2030 if (cChoice.substring(0, 1) == '#') {
2031 this.pageNum = parseInt(cChoice.slice(1));
2032 return;
2033 }
2034
2035 // Fallback: some viewers return cName instead of cReturn
2036 var url = cChoice;
2037 if (url.substring(0, 4) != 'http' && url.substring(0, 4) != 'file') {
2038 var idx = url.indexOf('http');
2039 if (idx < 0) idx = url.indexOf('file:');
2040 if (idx >= 0) url = url.substring(idx);
2041 else return;
2042 }
2043
2044 if (url.substring(0, 8) == 'file:///') app.openDoc(url.substring(7));
2045 else if (url.substring(0, 7) == 'file://') app.openDoc('//' + url.substring(7));
2046 else app.launchURL(url);
2047}
2048)JS";
2049
2050 fmt::print( m_outputFile,
2051 "<< /JavaScript\n"
2052 " << /Names\n"
2053 " [ (JSInit) << /Type /Action /S /JavaScript /JS {} >> ]\n"
2054 " >>\n"
2055 ">>\n",
2056 encodeStringForPlotter( js ) );
2057
2059 }
2060}
2061
2062
2064{
2065 // We can end up here if there was nothing to plot
2066 if( !m_outputFile )
2067 return false;
2068
2069 // Close the current page (often the only one)
2070 ClosePage();
2071
2072 if( !m_3dExportMode )
2074
2075 /* The page tree: it's a B-tree but luckily we only have few pages!
2076 So we use just an array... The handle was allocated at the beginning,
2077 now we instantiate the corresponding object */
2079 fmt::print( m_outputFile,
2080 "<<\n"
2081 "/Type /Pages\n"
2082 "/Kids [\n" );
2083
2084 for( unsigned i = 0; i < m_pageHandles.size(); i++ )
2085 fmt::println( m_outputFile, "{} 0 R", m_pageHandles[i] );
2086
2087 fmt::print( m_outputFile,
2088 "]\n"
2089 "/Count {}\n"
2090 ">>\n", m_pageHandles.size() );
2092
2093 int infoDictHandle = startPdfObject();
2094
2095 std::time_t time = std::time( nullptr );
2096 std::tm tm{};
2097#if defined( _WIN32 ) || defined( _MSC_VER )
2098 localtime_s( &tm, &time );
2099#else
2100 localtime_r( &time, &tm );
2101#endif
2102 std::string dt = fmt::format( "D:{:%Y:%m:%d:%H:%M:%S}", tm );
2103
2104 if( m_title.IsEmpty() )
2105 {
2106 // Windows uses '\' and other platforms use '/' as separator
2107 m_title = m_filename.AfterLast( '\\' );
2108 m_title = m_title.AfterLast( '/' );
2109 }
2110
2111 fmt::print( m_outputFile,
2112 "<<\n"
2113 "/Producer (KiCad PDF)\n"
2114 "/CreationDate ({})\n"
2115 "/Creator {}\n"
2116 "/Title {}\n"
2117 "/Author {}\n"
2118 "/Subject {}\n",
2119 dt,
2124
2125 fmt::println( m_outputFile, ">>" );
2127
2128 // Let's dump in the outline
2129 int outlineHandle = -1;
2130
2131 if( !m_3dExportMode )
2132 outlineHandle = emitOutline();
2133
2134 // The catalog, at last
2135 int catalogHandle = startPdfObject();
2136
2137 if( outlineHandle > 0 )
2138 {
2139 fmt::println( m_outputFile,
2140 "<<\n"
2141 "/Type /Catalog\n"
2142 "/Pages {} 0 R\n"
2143 "/Version /1.5\n"
2144 "/PageMode /UseOutlines\n"
2145 "/Outlines {} 0 R\n"
2146 "/Names {} 0 R\n"
2147 "/PageLayout /SinglePage\n"
2148 ">>",
2150 outlineHandle,
2152 }
2153 else
2154 {
2155 fmt::println( m_outputFile,
2156 "<<\n"
2157 "/Type /Catalog\n"
2158 "/Pages {} 0 R\n"
2159 "/Version /1.5\n"
2160 "/PageMode /UseNone\n"
2161 "/PageLayout /SinglePage\n"
2162 ">>",
2164 }
2165
2167
2168 /* Emit the xref table (format is crucial to the byte, each entry must
2169 be 20 bytes long, and object zero must be done in that way). Also
2170 the offset must be kept along for the trailer */
2171 long xref_start = ftell( m_outputFile );
2172 const std::vector<long>& xrefEntries = m_xrefTable.Entries();
2173
2174 fmt::print( m_outputFile,
2175 "xref\n"
2176 "0 {}\n"
2177 "0000000000 65535 f \n",
2178 xrefEntries.size() );
2179
2180 for( unsigned i = 1; i < xrefEntries.size(); i++ )
2181 fmt::print( m_outputFile, "{:010d} 00000 n \n", xrefEntries[i] );
2182
2183 // Done the xref, go for the trailer
2184 fmt::print( m_outputFile,
2185 "trailer\n"
2186 "<< /Size {} /Root {} 0 R /Info {} 0 R >>\n"
2187 "startxref\n"
2188 "{}\n" // The offset we saved before
2189 "%%EOF\n",
2190 xrefEntries.size(),
2191 catalogHandle,
2192 infoDictHandle,
2193 xref_start );
2194
2195 fclose( m_outputFile );
2196 m_outputFile = nullptr;
2197
2198 return true;
2199}
2200
2201
2202void PDF_PLOTTER::Text( const VECTOR2I& aPos, const COLOR4D& aColor, const wxString& aText, const EDA_ANGLE& aOrient,
2203 const VECTOR2I& aSize, enum GR_TEXT_H_ALIGN_T aH_justify, enum GR_TEXT_V_ALIGN_T aV_justify,
2204 int aWidth, bool aItalic, bool aBold, bool aMultilineAllowed, KIFONT::FONT* aFont,
2205 const KIFONT::METRICS& aFontMetrics, void* aData )
2206{
2207 // PDF files do not like 0 sized texts which create broken files.
2208 if( aSize.x == 0 || aSize.y == 0 )
2209 return;
2210
2211 wxString text( aText );
2212
2213 if( text.Contains( wxS( "@{" ) ) )
2214 {
2215 EXPRESSION_EVALUATOR evaluator;
2216 text = evaluator.Evaluate( text );
2217 }
2218
2219 if( !aFont )
2220 aFont = KIFONT::FONT::GetFont( m_renderSettings->GetDefaultFont() );
2221
2222 if( aFont->IsOutline() )
2223 {
2224 KIFONT::OUTLINE_FONT* outlineFont = static_cast<KIFONT::OUTLINE_FONT*>( aFont );
2226
2229 {
2230 // If we're not allowed to embed the fonts, then the PDF text plotting code won't work. In that
2231 // case we have to fall back to the standard text plotting (using a CALLBACK_GAL), and render
2232 // phantom text (which will be searchable) behind the stroke font. This is a long way from ideal,
2233 // but it is what it is.
2234 int render_mode = 3; // invisible
2235
2236 VECTOR2I pos( aPos );
2237 const char *fontname = aItalic ? ( aBold ? "/KicadFontBI" : "/KicadFontI" )
2238 : ( aBold ? "/KicadFontB" : "/KicadFont" );
2239
2240 m_usedBase14Fonts = true;
2241
2242 // Compute the copious transformation parameters of the Current Transform Matrix
2243 double ctm_a, ctm_b, ctm_c, ctm_d, ctm_e, ctm_f;
2244 double wideningFactor, heightFactor;
2245
2246 VECTOR2I t_size( std::abs( aSize.x ), std::abs( aSize.y ) );
2247 bool textMirrored = aSize.x < 0;
2248
2249 computeTextParameters( aPos, text, aOrient, t_size, textMirrored, aH_justify, aV_justify, aWidth,
2250 aItalic, aBold, &wideningFactor, &ctm_a, &ctm_b, &ctm_c, &ctm_d, &ctm_e, &ctm_f,
2251 &heightFactor );
2252
2253 SetColor( aColor );
2254 SetCurrentLineWidth( aWidth, aData );
2255
2256 wxStringTokenizer str_tok( text, " ", wxTOKEN_RET_DELIMS );
2257
2258 VECTOR2I full_box( aFont->StringBoundaryLimits( text, t_size, aWidth, aBold, aItalic, aFontMetrics ) );
2259
2260 if( textMirrored )
2261 full_box.x *= -1;
2262
2263 VECTOR2I box_x( full_box.x, 0 );
2264 VECTOR2I box_y( 0, full_box.y );
2265
2266 RotatePoint( box_x, aOrient );
2267 RotatePoint( box_y, aOrient );
2268
2269 if( aH_justify == GR_TEXT_H_ALIGN_CENTER )
2270 pos -= box_x / 2;
2271 else if( aH_justify == GR_TEXT_H_ALIGN_RIGHT )
2272 pos -= box_x;
2273
2274 if( aV_justify == GR_TEXT_V_ALIGN_CENTER )
2275 pos += box_y / 2;
2276 else if( aV_justify == GR_TEXT_V_ALIGN_TOP )
2277 pos += box_y;
2278
2279 while( str_tok.HasMoreTokens() )
2280 {
2281 wxString word = str_tok.GetNextToken();
2282
2283 computeTextParameters( pos, word, aOrient, t_size, textMirrored, GR_TEXT_H_ALIGN_LEFT,
2284 GR_TEXT_V_ALIGN_BOTTOM, aWidth, aItalic, aBold, &wideningFactor,
2285 &ctm_a, &ctm_b, &ctm_c, &ctm_d, &ctm_e, &ctm_f, &heightFactor );
2286
2287 // Extract the changed width and rotate by the orientation to get the offset for the
2288 // next word
2289 VECTOR2I bbox( aFont->StringBoundaryLimits( word, t_size, aWidth, aBold, aItalic, aFontMetrics ).x, 0 );
2290
2291 if( textMirrored )
2292 bbox.x *= -1;
2293
2294 RotatePoint( bbox, aOrient );
2295 pos += bbox;
2296
2297 // Don't try to output a blank string
2298 if( word.Trim( false ).Trim( true ).empty() )
2299 continue;
2300
2301 /* We use the full CTM instead of the text matrix because the same
2302 coordinate system will be used for the overlining. Also the %f
2303 for the trig part of the matrix to avoid %g going in exponential
2304 format (which is not supported) */
2305 fmt::print( m_workFile, "q {:f} {:f} {:f} {:f} {:f} {:f} cm BT {} {:g} Tf {} Tr {:g} Tz ",
2306 ctm_a, ctm_b, ctm_c, ctm_d, ctm_e, ctm_f,
2307 fontname,
2308 heightFactor,
2309 render_mode,
2310 wideningFactor * 100 );
2311
2312 std::string txt_pdf = encodeStringForPlotter( word );
2313 fmt::println( m_workFile, "{} Tj ET", txt_pdf );
2314 // Restore the CTM
2315 fmt::println( m_workFile, "Q" );
2316 }
2317
2318 // Plot the text
2319 PLOTTER::Text( aPos, aColor, text, aOrient, aSize, aH_justify, aV_justify, aWidth, aItalic,
2320 aBold, aMultilineAllowed, aFont, aFontMetrics, aData );
2321
2322 return;
2323 }
2324 }
2325
2326 SetColor( aColor );
2327 SetCurrentLineWidth( aWidth, aData );
2328
2329 VECTOR2I t_size( std::abs( aSize.x ), std::abs( aSize.y ) );
2330 bool textMirrored = aSize.x < 0;
2331
2332 if( aWidth == 0 && aBold )
2333 aWidth = GetPenSizeForBold( std::min( t_size.x, t_size.y ) );
2334
2335 if( aWidth < 0 )
2336 aWidth = -aWidth;
2337
2338 if( !aFont )
2339 aFont = KIFONT::FONT::GetFont( m_renderSettings->GetDefaultFont() );
2340
2341 auto computeAlignedStartPos =
2342 [&]()
2343 {
2344 VECTOR2I startPos( aPos );
2345
2346 if( aFont->IsStroke() )
2347 {
2348 TEXT_ATTRIBUTES alignAttrs;
2349 alignAttrs.m_Size = t_size;
2350 alignAttrs.m_StrokeWidth = aWidth;
2351 alignAttrs.m_Halign = aH_justify;
2352 alignAttrs.m_Valign = aV_justify;
2353 alignAttrs.m_Bold = aBold;
2354 alignAttrs.m_Italic = aItalic;
2355
2356 // getLinePositions returns anchor + offset; use (0,0) to get the offset alone.
2357 VECTOR2I drawOffset = aFont->GetAlignedDrawPosition( text, VECTOR2I( 0, 0 ), alignAttrs,
2358 aFontMetrics );
2359
2360 // GAL mirrors about the text anchor (GetDrawPos), after placing the unmirrored
2361 // cursor. Negating the X offset before rotation makes the Type3 Tz=-100 origin
2362 // land on the mirrored start so ink sits on the correct side of the anchor.
2363 if( textMirrored )
2364 drawOffset.x = -drawOffset.x;
2365
2366 RotatePoint( drawOffset, aOrient );
2367 startPos = aPos + drawOffset;
2368 }
2369 else
2370 {
2371 VECTOR2I full_box( aFont->StringBoundaryLimits( text, t_size, aWidth, aBold, aItalic,
2372 aFontMetrics ) );
2373
2374 if( textMirrored )
2375 full_box.x *= -1;
2376
2377 VECTOR2I box_x( full_box.x, 0 );
2378 VECTOR2I box_y( 0, full_box.y );
2379
2380 RotatePoint( box_x, aOrient );
2381 RotatePoint( box_y, aOrient );
2382
2383 if( aH_justify == GR_TEXT_H_ALIGN_CENTER )
2384 startPos -= box_x / 2;
2385 else if( aH_justify == GR_TEXT_H_ALIGN_RIGHT )
2386 startPos -= box_x;
2387
2388 if( aV_justify == GR_TEXT_V_ALIGN_CENTER )
2389 startPos += box_y / 2;
2390 else if( aV_justify == GR_TEXT_V_ALIGN_TOP )
2391 startPos += box_y;
2392 }
2393
2394 return startPos;
2395 };
2396
2397 // Parse the text for markup
2398 // IMPORTANT: Use explicit UTF-8 encoding. wxString::ToStdString() is locale-dependent
2399 // and under C/POSIX locale can drop or mangle non-ASCII, leading to missing CMaps.
2400 // The markup parser expects UTF-8 bytes.
2401 UTF8 utf8Text( text );
2402 MARKUP::MARKUP_PARSER markupParser( utf8Text.substr() );
2403 std::unique_ptr<MARKUP::NODE> markupTree( markupParser.Parse() );
2404
2405 if( !markupTree )
2406 {
2407 wxLogTrace( tracePdfPlotter, "PDF_PLOTTER::Text: Markup parsing failed, falling back to plain text." );
2408 // Fallback to simple text rendering if parsing fails
2409 wxStringTokenizer str_tok( text, " ", wxTOKEN_RET_DELIMS );
2410 VECTOR2I pos = computeAlignedStartPos();
2411
2412 while( str_tok.HasMoreTokens() )
2413 {
2414 wxString word = str_tok.GetNextToken();
2415 pos = renderWord( word, pos, t_size, aOrient, textMirrored, aWidth, aBold, aItalic, aFont,
2416 aFontMetrics, aV_justify, 0 );
2417 }
2418 return;
2419 }
2420
2421 VECTOR2I pos = computeAlignedStartPos();
2422
2423 // Render markup tree
2424 std::vector<OVERBAR_INFO> overbars;
2425 renderMarkupNode( markupTree.get(), pos, t_size, aOrient, textMirrored, aWidth, aBold, aItalic, aFont,
2426 aFontMetrics, aV_justify, 0, overbars );
2427
2428 // Draw any overbars that were accumulated
2429 drawOverbars( overbars, aOrient, aFontMetrics );
2430}
2431
2432
2433VECTOR2I PDF_PLOTTER::renderWord( const wxString& aWord, const VECTOR2I& aPosition, const VECTOR2I& aSize,
2434 const EDA_ANGLE& aOrient, bool aTextMirrored, int aWidth, bool aBold, bool aItalic,
2435 KIFONT::FONT* aFont, const KIFONT::METRICS& aFontMetrics,
2436 enum GR_TEXT_V_ALIGN_T aV_justify, TEXT_STYLE_FLAGS aTextStyle )
2437{
2438 if( wxGetEnv( "KICAD_DEBUG_SYN_STYLE", nullptr ) )
2439 {
2440 int styleFlags = 0;
2441
2442 if( aFont->IsOutline() )
2443 {
2444 if( const FT_Face& face = static_cast<KIFONT::OUTLINE_FONT*>( aFont )->GetFace() )
2445 styleFlags = (int) face->style_flags;
2446 }
2447
2448 wxLogTrace( tracePdfPlotter, "renderWord enter word='%s' bold=%d italic=%d textStyle=%u styleFlags=%d",
2449 TO_UTF8( aWord ), (int) aBold, (int) aItalic, (unsigned) aTextStyle, styleFlags );
2450 }
2451
2452 // Don't try to output a blank string, but handle space characters for word separation
2453 if( aWord.empty() )
2454 return aPosition;
2455
2456 // Compute the per-word cursor advance via the font's own glyph metrics so the gap between
2457 // words matches what the PDF Tj operator further down will produce. StringBoundaryLimits
2458 // would inflate the stroke-font bbox by 3*thickness, opening spurious whitespace between
2459 // words (issue #24419).
2460 //
2461 // Only BOLD/ITALIC from the caller are forwarded; SUPERSCRIPT/SUBSCRIPT in aTextStyle have
2462 // already been baked into aSize by renderMarkupNode, and Tj renders with that reduced Tf
2463 // size, so GetTextAsGlyphs must not apply the SUPER_SUB_SIZE_MULTIPLIER a second time.
2464 TEXT_STYLE_FLAGS metricsStyle = 0;
2465
2466 if( aBold )
2467 metricsStyle |= TEXT_STYLE::BOLD;
2468
2469 if( aItalic )
2470 metricsStyle |= TEXT_STYLE::ITALIC;
2471
2472 auto cursorAdvanceX =
2473 [&]( const wxString& aText )
2474 {
2475 return aFont->GetTextAsGlyphs( nullptr, nullptr, aText, aSize, VECTOR2I(), ANGLE_0,
2476 false, VECTOR2I(), metricsStyle ).x;
2477 };
2478
2479 // If the word is just a space character, advance position by space width and continue
2480 if( aWord == wxT( " " ) )
2481 {
2482 VECTOR2I spaceBox( cursorAdvanceX( wxT( " " ) ), 0 );
2483
2484 if( aTextMirrored )
2485 spaceBox.x *= -1;
2486
2487 VECTOR2I rotatedSpaceBox = spaceBox;
2488 RotatePoint( rotatedSpaceBox, aOrient );
2489 return aPosition + rotatedSpaceBox;
2490 }
2491
2492 // Tabs are layout only. Plot visible runs at font layout positions.
2493 if( aWord.Contains( wxT( '\t' ) ) )
2494 {
2495 auto positionedAdvance =
2496 [&]( const wxString& aText )
2497 {
2498 VECTOR2I advance( cursorAdvanceX( aText ), 0 );
2499
2500 if( aTextMirrored )
2501 advance.x *= -1;
2502
2503 RotatePoint( advance, aOrient );
2504 return advance;
2505 };
2506
2507 wxString prefix;
2508 wxString segment;
2509
2510 auto flushSegment =
2511 [&]()
2512 {
2513 if( !segment.IsEmpty() )
2514 {
2515 renderWord( segment, aPosition + positionedAdvance( prefix ), aSize, aOrient, aTextMirrored,
2516 aWidth, aBold, aItalic, aFont, aFontMetrics, aV_justify, aTextStyle );
2517 prefix += segment;
2518 segment.clear();
2519 }
2520 };
2521
2522 for( wxUniChar c : aWord )
2523 {
2524 if( c == '\t' )
2525 {
2526 flushSegment();
2527 prefix += c;
2528 }
2529 else
2530 {
2531 segment += c;
2532 }
2533 }
2534
2535 flushSegment();
2536
2537 return aPosition + positionedAdvance( aWord );
2538 }
2539
2540 VECTOR2I inkPos( aPosition );
2541
2542 if( aTextStyle & ( TEXT_STYLE::SUPERSCRIPT | TEXT_STYLE::SUBSCRIPT ) )
2543 {
2544 VECTOR2I offset( 0, KiROUND( aSize.y * aFont->GetSuperSubBaselineOffset( aTextStyle ) ) );
2545
2546 RotatePoint( offset, aOrient );
2547 inkPos += offset;
2548 }
2549
2550 // Compute transformation parameters for this word
2551 double ctm_a, ctm_b, ctm_c, ctm_d, ctm_e, ctm_f;
2552 double wideningFactor, heightFactor;
2553
2554 computeTextParameters( inkPos, aWord, aOrient, aSize, aTextMirrored, GR_TEXT_H_ALIGN_LEFT, GR_TEXT_V_ALIGN_BOTTOM,
2555 aWidth, aItalic, aBold, &wideningFactor, &ctm_a, &ctm_b, &ctm_c, &ctm_d, &ctm_e, &ctm_f,
2556 &heightFactor );
2557
2558 VECTOR2I bbox( cursorAdvanceX( aWord ), 0 );
2559
2560 if( aTextMirrored )
2561 bbox.x *= -1;
2562
2563 RotatePoint( bbox, aOrient );
2564 VECTOR2I nextPos = aPosition + bbox;
2565
2566 // Render the word using existing outline font logic
2567 if( aFont->IsOutline() )
2568 {
2569 std::vector<PDF_OUTLINE_FONT_RUN> outlineRuns;
2570
2572 {
2573 m_outlineFontManager->EncodeString( aWord, static_cast<KIFONT::OUTLINE_FONT*>( aFont ),
2574 ( aItalic || ( aTextStyle & TEXT_STYLE::ITALIC ) ),
2575 ( aBold || ( aTextStyle & TEXT_STYLE::BOLD ) ),
2576 &outlineRuns );
2577 }
2578
2579 if( !outlineRuns.empty() )
2580 {
2581 // Apply baseline adjustment (keeping existing logic)
2582 double baseline_factor = 0.17;
2583 double alignment_multiplier = 1.0;
2584
2585 if( aV_justify == GR_TEXT_V_ALIGN_CENTER )
2586 alignment_multiplier = 2.0;
2587 else if( aV_justify == GR_TEXT_V_ALIGN_TOP )
2588 alignment_multiplier = 4.0;
2589
2590 VECTOR2D font_size_dev = userToDeviceSize( aSize );
2591 double lineHeight = font_size_dev.y;
2592
2593 if( aTextStyle & ( TEXT_STYLE::SUPERSCRIPT | TEXT_STYLE::SUBSCRIPT ) )
2594 lineHeight /= aFont->GetSuperSubSizeMultiplier();
2595
2596 double baseline_adjustment = lineHeight * baseline_factor * alignment_multiplier;
2597
2598 double adjusted_ctm_e = ctm_e;
2599 double adjusted_ctm_f = ctm_f;
2600
2601 double angle_rad = aOrient.AsRadians();
2602 double cos_angle = cos( angle_rad );
2603 double sin_angle = sin( angle_rad );
2604
2605 adjusted_ctm_e = ctm_e - baseline_adjustment * sin_angle;
2606 adjusted_ctm_f = ctm_f + baseline_adjustment * cos_angle;
2607
2608 double adj_c = ctm_c;
2609 double adj_d = ctm_d;
2610
2611 // Synthetic italic (shear) for outline font if requested but font not intrinsically italic
2612 bool syntheticItalicApplied = false;
2613 double appliedTilt = 0.0;
2614 double syn_c = adj_c;
2615 double syn_d = adj_d;
2616 double syn_a = ctm_a;
2617 double syn_b = ctm_b;
2618 bool wantItalic = ( aItalic || ( aTextStyle & TEXT_STYLE::ITALIC ) );
2619
2620 if( std::getenv( "KICAD_FORCE_SYN_ITALIC" ) )
2621 wantItalic = true; // debug: ensure path triggers when forcing synthetic italic
2622
2623 bool wantBold = ( aBold || ( aTextStyle & TEXT_STYLE::BOLD ) );
2624 bool fontIsItalic = aFont->IsItalic();
2625 bool fontIsBold = aFont->IsBold();
2626 bool fontIsFakeItalic = static_cast<KIFONT::OUTLINE_FONT*>( aFont )->IsFakeItalic();
2627 bool fontIsFakeBold = static_cast<KIFONT::OUTLINE_FONT*>( aFont )->IsFakeBold();
2628
2629 // Environment overrides for testing synthetic italics:
2630 // KICAD_FORCE_SYN_ITALIC=1 forces synthetic shear even if font has italic face
2631 // KICAD_SYN_ITALIC_TILT=<float degrees or tangent?>: if value contains 'deg' treat as degrees,
2632 // otherwise treat as raw tilt factor (x += tilt*y)
2633 bool forceSynItalic = false;
2634 double overrideTilt = 0.0;
2635
2636 if( const char* envForce = std::getenv( "KICAD_FORCE_SYN_ITALIC" ) )
2637 {
2638 if( *envForce != '\0' && *envForce != '0' )
2639 forceSynItalic = true;
2640 }
2641
2642 if( const char* envTilt = std::getenv( "KICAD_SYN_ITALIC_TILT" ) )
2643 {
2644 std::string tiltStr( envTilt );
2645
2646 try
2647 {
2648 if( tiltStr.find( "deg" ) != std::string::npos )
2649 {
2650 double deg = std::stod( tiltStr );
2651 overrideTilt = tan( deg * M_PI / 180.0 );
2652 }
2653 else
2654 {
2655 overrideTilt = std::stod( tiltStr );
2656 }
2657 }
2658 catch( ... )
2659 {
2660 overrideTilt = 0.0; // ignore malformed
2661 }
2662 }
2663
2664 // Trace after we know style flags
2665 wxLogTrace( tracePdfPlotter, "Outline path word='%s' runs=%zu wantItalic=%d fontIsItalic=%d "
2666 "fontIsFakeItalic=%d wantBold=%d fontIsBold=%d fontIsFakeBold=%d forceSyn=%d",
2667 TO_UTF8( aWord ), outlineRuns.size(), (int) wantItalic, (int) fontIsItalic,
2668 (int) fontIsFakeItalic, (int) wantBold, (int) fontIsBold, (int) fontIsFakeBold,
2669 (int) forceSynItalic );
2670
2671 // Apply synthetic italic if:
2672 // - Italic requested AND outline font
2673 // - And either forceSynItalic env var set OR there is no REAL italic face.
2674 // (A fake italic flag from fontconfig substitution should NOT block synthetic shear.)
2675 bool realItalicFace = fontIsItalic && !fontIsFakeItalic;
2676
2677 if( wantItalic && ( forceSynItalic || !realItalicFace ) )
2678 {
2679 // We want to apply a horizontal shear so that x' = x + tilt * y in the glyph's
2680 // local coordinate system BEFORE rotation. The existing text matrix columns are:
2681 // first column = (a, b)^T -> x-axis direction & scale
2682 // second column = (c, d)^T -> y-axis direction & scale
2683 // Prepending a shear matrix S = [[1 tilt][0 1]] (i.e. T' = T * S is WRONG here).
2684 // We need to LEFT-multiply: T' = R * S where R is the original rotation/scale.
2685 // Left multiplication keeps first column unchanged and adds (tilt * firstColumn)
2686 // to the second column: (c', d') = (c + tilt * a, d + tilt * b).
2687 // This produces a right-leaning italic for positive tilt.
2688 double tilt = ( overrideTilt != 0.0 ) ? overrideTilt : ITALIC_TILT;
2689
2690 if( wideningFactor < 0 ) // mirrored text should mirror the shear
2691 tilt = -tilt;
2692
2693 syn_c = adj_c + tilt * syn_a;
2694 syn_d = adj_d + tilt * syn_b;
2695 appliedTilt = tilt;
2696 syntheticItalicApplied = true;
2697
2698 wxLogTrace( tracePdfPlotter, "Synthetic italic shear applied: tilt=%f a=%f b=%f c->%f d->%f",
2699 tilt, syn_a, syn_b, syn_c, syn_d );
2700 }
2701
2702 if( wantBold && !fontIsBold )
2703 {
2704 // Slight horizontal widening to simulate bold (~3%)
2705 syn_a *= 1.03;
2706 syn_b *= 1.03;
2707 }
2708
2709 if( syntheticItalicApplied )
2710 {
2711 // PDF comment to allow manual inspection in the output stream
2712 fmt::print( m_workFile, "% syn-italic tilt={} a={} b={} c={} d={}\n",
2713 appliedTilt, syn_a, syn_b, syn_c, syn_d );
2714 }
2715
2716 fmt::print( m_workFile, "q {:f} {:f} {:f} {:f} {:f} {:f} cm BT {} Tr {} Tz ",
2717 syn_a, syn_b, syn_c, syn_d, adjusted_ctm_e, adjusted_ctm_f,
2718 0, // render_mode
2719 encodeDoubleForPlotter( wideningFactor * 100 ) );
2720
2721 for( const PDF_OUTLINE_FONT_RUN& run : outlineRuns )
2722 {
2723 fmt::print( m_workFile, "{} {} Tf <",
2724 run.m_subset->ResourceName(),
2725 encodeDoubleForPlotter( heightFactor ) );
2726
2727 for( const PDF_OUTLINE_FONT_GLYPH& glyph : run.m_glyphs )
2728 {
2729 fmt::print( m_workFile, "{:02X}{:02X}",
2730 static_cast<unsigned char>( ( glyph.cid >> 8 ) & 0xFF ),
2731 static_cast<unsigned char>( glyph.cid & 0xFF ) );
2732 }
2733
2734 fmt::print( m_workFile, "> Tj " );
2735 }
2736
2737 fmt::println( m_workFile, "ET" );
2738 fmt::println( m_workFile, "Q" );
2739 }
2740 }
2741 else
2742 {
2743 // Handle stroke fonts
2744 if( !m_strokeFontManager )
2745 return nextPos;
2746
2747 wxLogTrace( tracePdfPlotter, "Stroke path word='%s' wantItalic=%d aItalic=%d aBold=%d",
2748 TO_UTF8( aWord ), (int) ( aItalic || ( aTextStyle & TEXT_STYLE::ITALIC ) ),
2749 (int) aItalic, (int) aBold );
2750
2751 std::vector<PDF_STROKE_FONT_RUN> runs;
2752 m_strokeFontManager->EncodeString( aWord, &runs, aWidth, aSize.x, aSize.y, aBold, aItalic );
2753
2754 if( !runs.empty() )
2755 {
2756 VECTOR2D dev_size = userToDeviceSize( aSize );
2757 double fontSize = dev_size.y;
2758
2759 double adj_c = ctm_c;
2760 double adj_d = ctm_d;
2761
2762 if( aItalic )
2763 {
2764 double tilt = -ITALIC_TILT;
2765
2766 if( wideningFactor < 0 )
2767 tilt = -tilt;
2768
2769 adj_c -= ctm_a * tilt;
2770 adj_d -= ctm_b * tilt;
2771 }
2772
2773 // Cancel m_PDFStrokeFontXOffset / m_PDFStrokeFontYOffset baked into Type3 charprocs.
2774 // Horizontal/vertical anchors are already GAL-aligned in PDF_PLOTTER::Text().
2775 // X offset is stored in aspect-scaled glyph X units, so cancel with device width.
2776 // When Tz mirrors (wideningFactor < 0), glyph X is flipped, so cancel the other way.
2777 const double xOffsetEm = ADVANCED_CFG::GetCfg().m_PDFStrokeFontXOffset;
2778 const double yOffsetEm = ADVANCED_CFG::GetCfg().m_PDFStrokeFontYOffset;
2779 const double xCancelDev = xOffsetEm * dev_size.x;
2780 const double yCancelDev = yOffsetEm * dev_size.y;
2781 const double xSign = ( wideningFactor < 0 ) ? -1.0 : 1.0;
2782
2783 const double adj_ctm_e = ctm_e - yCancelDev * adj_c - xSign * xCancelDev * ctm_a;
2784 const double adj_ctm_f = ctm_f - yCancelDev * adj_d - xSign * xCancelDev * ctm_b;
2785
2786 // Aspect ratio is baked into the Type3 glyph charprocs; Tz only mirrors when needed.
2787 const double tzFactor = wideningFactor < 0 ? -100.0 : 100.0;
2788
2789 fmt::print( m_workFile, "q {:f} {:f} {:f} {:f} {:f} {:f} cm BT {} Tr {} Tz ",
2790 ctm_a, ctm_b, adj_c, adj_d, adj_ctm_e, adj_ctm_f,
2791 0, // render_mode
2792 encodeDoubleForPlotter( tzFactor ) );
2793
2794 for( const PDF_STROKE_FONT_RUN& run : runs )
2795 {
2796 fmt::print( m_workFile, "{} {} Tf {} Tj ",
2797 run.m_subset->ResourceName(),
2798 encodeDoubleForPlotter( fontSize ),
2799 encodeByteString( run.m_bytes ) );
2800 }
2801
2802 fmt::println( m_workFile, "ET" );
2803 fmt::println( m_workFile, "Q" );
2804 }
2805 }
2806
2807 return nextPos;
2808}
2809
2810
2812 const VECTOR2I& aBaseSize, const EDA_ANGLE& aOrient,
2813 bool aTextMirrored, int aWidth, bool aBaseBold, bool aBaseItalic,
2814 KIFONT::FONT* aFont, const KIFONT::METRICS& aFontMetrics,
2815 enum GR_TEXT_V_ALIGN_T aV_justify, TEXT_STYLE_FLAGS aTextStyle,
2816 std::vector<OVERBAR_INFO>& aOverbars )
2817{
2818 VECTOR2I nextPosition = aPosition;
2819
2820 if( !aNode )
2821 return nextPosition;
2822
2823 TEXT_STYLE_FLAGS currentStyle = aTextStyle;
2824 VECTOR2I currentSize = aBaseSize;
2825 bool drawOverbar = false;
2826
2827 // Handle markup node types
2828 if( !aNode->is_root() )
2829 {
2830 if( aNode->isSubscript() || aNode->isSuperscript() )
2831 {
2832 currentStyle |= aNode->isSubscript() ? TEXT_STYLE::SUBSCRIPT : TEXT_STYLE::SUPERSCRIPT;
2833
2834 double scale = aFont->GetSuperSubSizeMultiplier();
2835
2836 currentSize = VECTOR2I( KiROUND( aBaseSize.x * scale ), KiROUND( aBaseSize.y * scale ) );
2837 }
2838
2839 if( aNode->isOverbar() )
2840 {
2841 drawOverbar = true;
2842 // Overbar doesn't change font size, just adds decoration
2843 }
2844
2845 // Render content of this node if it has text
2846 if( aNode->has_content() )
2847 {
2848 wxString nodeText = aNode->asWxString();
2849
2850 // Process text content (simplified version of the main text processing)
2851 wxStringTokenizer str_tok( nodeText, " ", wxTOKEN_RET_DELIMS );
2852
2853 while( str_tok.HasMoreTokens() )
2854 {
2855 wxString word = str_tok.GetNextToken();
2856 nextPosition = renderWord( word, nextPosition, currentSize, aOrient, aTextMirrored, aWidth,
2857 aBaseBold || (currentStyle & TEXT_STYLE::BOLD),
2858 aBaseItalic || (currentStyle & TEXT_STYLE::ITALIC),
2859 aFont, aFontMetrics, aV_justify, currentStyle );
2860 }
2861 }
2862 }
2863
2864 // Process child nodes recursively
2865 for( const std::unique_ptr<MARKUP::NODE>& child : aNode->children )
2866 {
2867 VECTOR2I startPos = nextPosition;
2868
2869 nextPosition = renderMarkupNode( child.get(), nextPosition, currentSize, aOrient, aTextMirrored, aWidth,
2870 aBaseBold, aBaseItalic, aFont, aFontMetrics, aV_justify, currentStyle,
2871 aOverbars );
2872
2873 // Store overbar info for later rendering
2874 if( drawOverbar )
2875 {
2876 VECTOR2I endPos = nextPosition;
2877 aOverbars.push_back( { startPos, endPos, currentSize, aFont->IsOutline(), aV_justify } );
2878 }
2879 }
2880
2881 return nextPosition;
2882}
2883
2884
2885void PDF_PLOTTER::drawOverbars( const std::vector<OVERBAR_INFO>& aOverbars, const EDA_ANGLE& aOrient,
2886 const KIFONT::METRICS& aFontMetrics )
2887{
2888 for( const OVERBAR_INFO& overbar : aOverbars )
2889 {
2890 // Baseline direction (vector from start to end). If zero length, derive from orientation.
2891 VECTOR2D dir( overbar.endPos.x - overbar.startPos.x, overbar.endPos.y - overbar.startPos.y );
2892
2893 double len = hypot( dir.x, dir.y );
2894
2895 if( len <= 1e-6 )
2896 {
2897 // Fallback: derive direction from orientation angle
2898 double ang = aOrient.AsRadians();
2899 dir.x = cos( ang );
2900 dir.y = sin( ang );
2901 len = 1.0;
2902 }
2903
2904 dir.x /= len;
2905 dir.y /= len;
2906
2907 // Perpendicular (rotate dir 90° CCW). Upward in text space so overbar sits above baseline.
2908 VECTOR2D nrm( -dir.y, dir.x );
2909
2910 // Base vertical offset distance in device units (baseline -> default overbar position)
2911 double barOffset = aFontMetrics.GetOverbarVerticalPosition( overbar.fontSize.y );
2912
2913 // Adjust further for outline fonts
2914 if( overbar.isOutline )
2915 barOffset += overbar.fontSize.y * 0.25; // extra raise for outline font
2916
2917 // Mirror the text vertical alignment adjustments used for baseline shifting.
2918 // Earlier logic scales baseline adjustment: CENTER ~2x, TOP ~4x. We apply proportional
2919 // extra raise so that overbars track visually with perceived baseline shift.
2920 double alignMult = 1.0;
2921
2922 switch( overbar.vAlign )
2923 {
2924 case GR_TEXT_V_ALIGN_CENTER: alignMult = overbar.isOutline ? 2.0 : 1.0; break;
2925 case GR_TEXT_V_ALIGN_TOP: alignMult = overbar.isOutline ? 4.0 : 1.0; break;
2926 default: alignMult = 1.0; break; // bottom
2927 }
2928
2929 if( alignMult > 1.0 )
2930 {
2931 // Scale only the baseline component (approx 17% of height, matching earlier baseline_factor)
2932 double baseline_factor = 0.17;
2933 barOffset += ( alignMult - 1.0 ) * ( baseline_factor * overbar.fontSize.y );
2934 }
2935
2936 // Trim to avoid rounded cap extension (assumes stroke caps); proportion of font width.
2937 double barTrim = overbar.fontSize.x * 0.1;
2938
2939 // Apply trim along baseline direction and offset along normal
2940 VECTOR2D startPt( overbar.startPos.x, overbar.startPos.y );
2941 VECTOR2D endPt( overbar.endPos.x, overbar.endPos.y );
2942
2943 // Both endpoints should share identical vertical (normal) offset above baseline.
2944 // Use a single offset vector offVec = -barOffset * nrm (negative because nrm points 'up').
2945 VECTOR2D offVec( -barOffset * nrm.x, -barOffset * nrm.y );
2946
2947 startPt.x += dir.x * barTrim + offVec.x;
2948 startPt.y += dir.y * barTrim + offVec.y;
2949 endPt.x -= dir.x * barTrim - offVec.x; // subtract trim, then apply same vertical offset
2950 endPt.y -= dir.y * barTrim - offVec.y;
2951
2952 VECTOR2I iStart = KiROUND( startPt.x, startPt.y );
2953 VECTOR2I iEnd = KiROUND( endPt.x, endPt.y );
2954
2955 MoveTo( iStart );
2956 LineTo( iEnd );
2957 PenFinish();
2958 }
2959}
2960
2961
2963 const COLOR4D& aColor,
2964 const wxString& aText,
2965 const TEXT_ATTRIBUTES& aAttributes,
2966 KIFONT::FONT* aFont,
2967 const KIFONT::METRICS& aFontMetrics,
2968 void* aData )
2969{
2970 VECTOR2I size = aAttributes.m_Size;
2971
2972 // PDF files do not like 0 sized texts which create broken files.
2973 if( size.x == 0 || size.y == 0 )
2974 return;
2975
2976 if( aAttributes.m_Mirrored )
2977 size.x = -size.x;
2978
2979 PDF_PLOTTER::Text( aPos, aColor, aText, aAttributes.m_Angle.GetAngle(), size, aAttributes.m_Halign, aAttributes.m_Valign,
2980 aAttributes.m_StrokeWidth, aAttributes.m_Italic, aAttributes.m_Bold, aAttributes.m_Multiline,
2981 aFont, aFontMetrics, aData );
2982}
2983
2984
2985void PDF_PLOTTER::HyperlinkBox( const BOX2I& aBox, const wxString& aDestinationURL )
2986{
2987 m_hyperlinksInPage.push_back( std::make_pair( aBox, aDestinationURL ) );
2988}
2989
2990
2991void PDF_PLOTTER::HyperlinkMenu( const BOX2I& aBox, const std::vector<wxString>& aDestURLs )
2992{
2993 m_hyperlinkMenusInPage.push_back( std::make_pair( aBox, aDestURLs ) );
2994}
2995
2996
2997void PDF_PLOTTER::Bookmark( const BOX2I& aLocation, const wxString& aSymbolReference, const wxString &aGroupName )
2998{
2999
3000 m_bookmarksInPage[aGroupName].push_back( std::make_pair( aLocation, aSymbolReference ) );
3001}
3002
3003
3004void PDF_PLOTTER::Plot3DModel( const wxString& aSourcePath, const std::vector<PDF_3D_VIEW>& a3DViews )
3005{
3006 std::map<float, int> m_fovMap;
3007 std::vector<int> m_viewHandles;
3008
3009 for( const PDF_3D_VIEW& view : a3DViews )
3010 {
3011 // this is a strict need
3012 wxASSERT( view.m_cameraMatrix.size() == 12 );
3013
3014 int fovHandle = -1;
3015 if( !m_fovMap.contains( view.m_fov ) )
3016 {
3017 fovHandle = allocPdfObject();
3018 m_fovMap[view.m_fov] = fovHandle;
3019
3020 startPdfObject( fovHandle );
3021 fmt::print( m_outputFile,
3022 "<<\n"
3023 "/FOV {}\n"
3024 "/PS /Min\n"
3025 "/Subtype /P\n"
3026 ">>\n",
3027 encodeDoubleForPlotter( view.m_fov ) );
3029 }
3030 else
3031 {
3032 fovHandle = m_fovMap[view.m_fov];
3033 }
3034
3035 int viewHandle = allocPdfObject();
3036 startPdfObject( viewHandle );
3037
3038 const std::string encodedName = encodeStringForPlotter( wxString::FromUTF8( view.m_name ) );
3039
3040 fmt::print( m_outputFile,
3041 "<<\n"
3042 "/Type /3DView\n"
3043 "/XN {}\n"
3044 "/IN {}\n"
3045 "/MS /M\n"
3046 "/C2W [{:f} {:f} {:f} {:f} {:f} {:f} {:f} {:f} {:f} {:f} {:f} {:f}]\n"
3047 "/CO {:f}\n"
3048 "/NR false\n"
3049 "/BG<<\n"
3050 "/Type /3DBG\n"
3051 "/Subtype /SC\n"
3052 "/CS /DeviceRGB\n"
3053 "/C [1.000000 1.000000 1.000000]>>\n"
3054 "/P {} 0 R\n"
3055 "/LS<<\n"
3056 "/Type /3DLightingScheme\n"
3057 "/Subtype /CAD>>\n"
3058 ">>\n",
3059 encodedName, encodedName,
3060 view.m_cameraMatrix[0],
3061 view.m_cameraMatrix[1],
3062 view.m_cameraMatrix[2], view.m_cameraMatrix[3], view.m_cameraMatrix[4],
3063 view.m_cameraMatrix[5], view.m_cameraMatrix[6], view.m_cameraMatrix[7],
3064 view.m_cameraMatrix[8], view.m_cameraMatrix[9], view.m_cameraMatrix[10],
3065 view.m_cameraMatrix[11],
3066 view.m_cameraCenter,
3067 fovHandle );
3068
3070
3071 m_viewHandles.push_back( viewHandle );
3072 }
3073
3075
3076 // so we can get remotely stuff the length afterwards
3077 int modelLenHandle = allocPdfObject();
3078
3079 fmt::print( m_outputFile,
3080 "<<\n"
3081 "/Type /3D\n"
3082 "/Subtype /U3D\n"
3083 "/DV 0\n" );
3084
3085 fmt::print( m_outputFile, "/VA [" );
3086
3087 for( int viewHandle : m_viewHandles )
3088 fmt::print( m_outputFile, "{} 0 R ", viewHandle );
3089
3090 fmt::print( m_outputFile, "]\n" );
3091
3092 fmt::print( m_outputFile,
3093 "/Length {} 0 R\n"
3094 "/Filter /FlateDecode\n"
3095 ">>\n", // Length is deferred
3096 modelLenHandle );
3097
3098 fmt::println( m_outputFile, "stream" );
3099
3100 wxFFile outputFFile( m_outputFile );
3101
3102 fflush( m_outputFile );
3103 long imgStreamStart = ftell( m_outputFile );
3104
3105 size_t model_stored_size = 0;
3106
3107 {
3108 wxFFileOutputStream ffos( outputFFile );
3109 wxZlibOutputStream zos( ffos, wxZ_BEST_COMPRESSION, wxZLIB_ZLIB );
3110
3111 wxFFileInputStream fileStream( aSourcePath );
3112
3113 if( !fileStream.IsOk() )
3114 wxLogError( _( "Failed to open 3D model file: %s" ), aSourcePath );
3115
3116 zos.Write( fileStream );
3117 }
3118
3119 fflush( m_outputFile );
3120 model_stored_size = ftell( m_outputFile );
3121 model_stored_size -= imgStreamStart; // Get the size of the compressed stream
3122
3123 fmt::print( m_outputFile, "\nendstream\n" );
3125
3126 startPdfObject( modelLenHandle );
3127 fmt::println( m_outputFile, "{}", (unsigned) model_stored_size );
3129
3130 outputFFile.Detach(); // Don't close it
3131}
3132
3133
3134std::vector<float> PDF_PLOTTER::CreateC2WMatrixFromAngles( const VECTOR3D& aTargetPosition,
3135 float aCameraDistance,
3136 float aYawDegrees,
3137 float aPitchDegrees,
3138 float aRollDegrees )
3139{
3140 float yRadians = glm::radians( aYawDegrees );
3141 float xRadians = glm::radians( aPitchDegrees );
3142 float zRadians = glm::radians( aRollDegrees );
3143
3144 // Create rotation matrix from Euler angles
3145 glm::mat4 rotationMatrix = glm::eulerAngleYXZ( yRadians, xRadians, zRadians );
3146
3147 // Calculate camera position based on target, distance, and rotation
3148 // Start with a vector pointing backward along the z-axis
3149 glm::vec4 cameraOffset = glm::vec4( 0.0f, 0.0f, aCameraDistance, 1.0f );
3150
3151 // Apply rotation to this offset
3152 cameraOffset = rotationMatrix * cameraOffset;
3153
3154 // Camera position is target position minus the rotated offset
3155 glm::vec3 cameraPosition = glm::vec3(aTargetPosition.x, aTargetPosition.y, aTargetPosition.z)
3156 - glm::vec3( cameraOffset );
3157
3158 std::vector<float> result( 12 );
3159
3160 // Handle rotation part in column-major order (first 9 elements)
3161 int index = 0;
3162 for( int col = 0; col < 3; ++col )
3163 {
3164 for( int row = 0; row < 3; ++row )
3165 result[index++] = static_cast<float>( rotationMatrix[col][row] );
3166 }
3167
3168 // Handle translation part (last 3 elements)
3169 result[9] = static_cast<float>( cameraPosition.x );
3170 result[10] = static_cast<float>( cameraPosition.y );
3171 result[11] = static_cast<float>( cameraPosition.z );
3172
3173 return result;
3174}
int index
void WriteImageStream(const wxImage &aImage, wxDataOutputStream &aOut, const wxColor &bg, bool colorMode)
void WriteImageSMaskStream(const wxImage &aImage, wxDataOutputStream &aOut)
BOX2< VECTOR2I > BOX2I
Definition box2.h:917
constexpr BOX2I KiROUND(const BOX2D &aBoxD)
Definition box2.h:985
BOX2< VECTOR2D > BOX2D
Definition box2.h:918
static const ADVANCED_CFG & GetCfg()
Get the singleton instance's config, which is shared by all consumers.
constexpr const Vec & GetPosition() const
Definition box2.h:214
constexpr const Vec GetEnd() const
Definition box2.h:215
constexpr void SetOrigin(const Vec &pos)
Definition box2.h:240
constexpr BOX2< Vec > & Normalize()
Ensure that the height and width are positive.
Definition box2.h:149
constexpr coord_type GetLeft() const
Definition box2.h:231
constexpr coord_type GetRight() const
Definition box2.h:220
constexpr void SetEnd(coord_type x, coord_type y)
Definition box2.h:300
constexpr coord_type GetTop() const
Definition box2.h:232
constexpr coord_type GetBottom() const
Definition box2.h:225
double AsRadians() const
Definition eda_angle.h:119
EDA_ANGLE GetAngle() const
Definition eda_angle.h:557
static bool IsGotoPageHref(const wxString &aHref, wxString *aDestination=nullptr)
Check if aHref is a valid internal hyperlink.
High-level wrapper for evaluating mathematical and string expressions in wxString format.
wxString Evaluate(const wxString &aInput)
Main evaluation function - processes input string and evaluates all '@{}' expressions.
FONT is an abstract base class for both outline and stroke fonts.
Definition font.h:94
static FONT * GetFont(const wxString &aFontName=wxEmptyString, bool aBold=false, bool aItalic=false, const std::vector< wxString > *aEmbeddedFiles=nullptr, bool aForDrawingSheet=false)
Definition font.cpp:144
virtual bool IsStroke() const
Definition font.h:101
virtual bool IsItalic() const
Definition font.h:104
virtual bool IsBold() const
Definition font.h:103
virtual bool IsOutline() const
Definition font.h:102
VECTOR2I GetAlignedDrawPosition(const wxString &aText, const VECTOR2I &aAnchor, const TEXT_ATTRIBUTES &aAttributes, const METRICS &aFontMetrics) const
Return the draw position for the first line of text, using the same alignment rules as GAL rendering ...
Definition font.cpp:472
VECTOR2I StringBoundaryLimits(const wxString &aText, const VECTOR2I &aSize, int aThickness, bool aBold, bool aItalic, const METRICS &aFontMetrics) const
Compute the boundary limits of aText (the bounding box of all shapes).
Definition font.cpp:442
virtual double GetSuperSubSizeMultiplier() const =0
Return the factor the text size is multiplied by for a superscript or subscript run.
virtual VECTOR2I GetTextAsGlyphs(BOX2I *aBBox, std::vector< std::unique_ptr< GLYPH > > *aGlyphs, const wxString &aText, const VECTOR2I &aSize, const VECTOR2I &aPosition, const EDA_ANGLE &aAngle, bool aMirror, const VECTOR2I &aOrigin, TEXT_STYLE_FLAGS aTextStyle) const =0
Convert text string to an array of GLYPHs.
virtual double GetSuperSubBaselineOffset(TEXT_STYLE_FLAGS aTextStyle) const =0
Return the baseline shift of a superscript or subscript run, as a downwards fraction of the reduced g...
double GetOverbarVerticalPosition(double aGlyphHeight) const
Compute the vertical position of an overbar.
Implement outline font drawing.
EMBEDDING_PERMISSION GetEmbeddingPermission() const
A color representation with 4 components: red, green, blue, alpha.
Definition color4d.h:101
std::unique_ptr< NODE > Parse()
XREF_TABLE m_xrefTable
The PDF xref offset table.
std::vector< int > m_pageHandles
Handles to the page objects.
FILE * m_workFile
Temporary file to construct the stream before zipping.
void emitOutlineFonts()
wxString m_parentPageName
virtual void ClosePage()
Close the current page in the PDF document (and emit its compressed stream).
void emitOutlineNode(OUTLINE_NODE *aNode, int aParentHandle, int aNextNode, int aPrevNode)
Emits a outline item object and recurses into any children.
std::map< int, wxImage > m_imageHandles
int emitOutline()
Starts emitting the outline object.
virtual bool EndPlot() override
int startPdfObject(int aHandle=-1)
Open a new PDF object and returns the handle if the parameter is -1.
virtual void PlotPoly(const std::vector< VECTOR2I > &aCornerList, FILL_T aFill, int aWidth=USE_DEFAULT_LINE_WIDTH, void *aData=nullptr) override
Polygon plotting for PDF.
virtual ~PDF_PLOTTER()
virtual void Circle(const VECTOR2I &pos, int diametre, FILL_T fill, int width) override
Circle drawing for PDF.
virtual void SetCurrentLineWidth(int width, void *aData=nullptr) override
Pen width setting for PDF.
double m_currentAlpha
Alpha currently set in the page graphics state (PDF starts each page with 1.0).
int m_streamLengthHandle
Handle to the deferred stream length.
int m_jsNamesHandle
Handle for Names dictionary with JS.
wxString m_pageName
virtual void SetDash(int aLineWidth, LINE_STYLE aLineStyle) override
PDF supports dashed lines.
void HyperlinkMenu(const BOX2I &aBox, const std::vector< wxString > &aDestURLs) override
Create a clickable hyperlink menu with a rectangular click area.
virtual bool OpenFile(const wxString &aFullFilename) override
Open or create the plot file aFullFilename.
std::string encodeDoubleForPlotter(double aValue) const
Convert a double to a PDF-compatible numeric token (no exponent notation).
int m_fontResDictHandle
Font resource dictionary.
virtual void emitSetRGBColor(double r, double g, double b, double a) override
PDF supports colors fully.
void emitStrokeFonts()
std::map< int, std::pair< BOX2D, wxString > > m_hyperlinkHandles
Handles for all the hyperlink objects that will be deferred.
int m_pageTreeHandle
Handle to the root of the page tree object.
std::map< double, int > m_alphaToExtGStateHandles
Graphics state objects keyed by alpha.
virtual void Text(const VECTOR2I &aPos, const COLOR4D &aColor, const wxString &aText, const EDA_ANGLE &aOrient, const VECTOR2I &aSize, enum GR_TEXT_H_ALIGN_T aH_justify, enum GR_TEXT_V_ALIGN_T aV_justify, int aWidth, bool aItalic, bool aBold, bool aMultilineAllowed, KIFONT::FONT *aFont, const KIFONT::METRICS &aFontMetrics, void *aData=nullptr) override
Draw text with the plotter.
int emitGoToAction(int aPageHandle, const VECTOR2I &aBottomLeft, const VECTOR2I &aTopRight)
Emit an action object that instructs a goto coordinates on a page.
void closePdfStream()
Finish the current PDF stream (writes the deferred length, too).
void Bookmark(const BOX2I &aBox, const wxString &aName, const wxString &aGroupName=wxEmptyString) override
Create a bookmark to a symbol.
void endPlotEmitResources()
virtual void Rect(const VECTOR2I &p1, const VECTOR2I &p2, FILL_T fill, int width, int aCornerRadius=0) override
Rectangles in PDF.
int startPdfStream(int aHandle=-1)
Start a PDF stream (for the page).
VECTOR2I renderMarkupNode(const MARKUP::NODE *aNode, const VECTOR2I &aPosition, const VECTOR2I &aBaseSize, const EDA_ANGLE &aOrient, bool aTextMirrored, int aWidth, bool aBaseBold, bool aBaseItalic, KIFONT::FONT *aFont, const KIFONT::METRICS &aFontMetrics, enum GR_TEXT_V_ALIGN_T aV_justify, TEXT_STYLE_FLAGS aTextStyle, std::vector< OVERBAR_INFO > &aOverbars)
Recursively render markup nodes with appropriate styling.
virtual void Arc(const VECTOR2D &aCenter, const EDA_ANGLE &aStartAngle, const EDA_ANGLE &aAngle, double aRadius, FILL_T aFill, int aWidth) override
The PDF engine can't directly plot arcs so we use polygonization.
void HyperlinkBox(const BOX2I &aBox, const wxString &aDestinationURL) override
Create a clickable hyperlink with a rectangular click area.
virtual void PenTo(const VECTOR2I &pos, char plume) override
Moveto/lineto primitive, moves the 'pen' to the specified direction.
int m_extGStateResDictHandle
Graphics state resource dictionary.
std::map< wxString, std::vector< std::pair< BOX2I, wxString > > > m_bookmarksInPage
virtual bool StartPlot(const wxString &aPageNumber) override
The PDF engine supports multiple pages; the first one is opened 'for free' the following are to be cl...
bool m_usedBase14Fonts
Set when the non-embeddable font fallback references the base-14 /KicadFont* resources.
int getExtGStateHandleForAlpha(double aAlpha)
Return the ExtGState resource handle for the given alpha, allocating a new object the first time that...
virtual void StartPage(const wxString &aPageNumber, const wxString &aPageName=wxEmptyString, const wxString &aParentPageNumber=wxEmptyString, const wxString &aParentPageName=wxEmptyString)
Start a new page in the PDF document.
std::unique_ptr< PDF_OUTLINE_FONT_MANAGER > m_outlineFontManager
OUTLINE_NODE * addOutlineNode(OUTLINE_NODE *aParent, int aActionHandle, const wxString &aTitle)
Add a new outline node entry.
int m_imgResDictHandle
Image resource dictionary.
std::string encodeStringForPlotter(const wxString &aUnicode) override
convert a wxString unicode string to a char string compatible with the accepted string PDF format (co...
std::unique_ptr< PDF_STROKE_FONT_MANAGER > m_strokeFontManager
void Plot3DModel(const wxString &aSourcePath, const std::vector< PDF_3D_VIEW > &a3DViews)
std::vector< wxString > m_pageNumbers
List of user-space page numbers for resolving internal hyperlinks.
int allocPdfObject()
Allocate a new handle in the table of the PDF object.
void PlotImage(const wxImage &aImage, const VECTOR2I &aPos, double aScaleFactor, double aAlpha) override
Plot a bitmap.
VECTOR2I renderWord(const wxString &aWord, const VECTOR2I &aPosition, const VECTOR2I &aSize, const EDA_ANGLE &aOrient, bool aTextMirrored, int aWidth, bool aBold, bool aItalic, KIFONT::FONT *aFont, const KIFONT::METRICS &aFontMetrics, enum GR_TEXT_V_ALIGN_T aV_justify, TEXT_STYLE_FLAGS aTextStyle)
Render a single word with the given style parameters.
wxString m_workFilename
std::string encodeByteString(const std::string &aBytes)
void drawOverbars(const std::vector< OVERBAR_INFO > &aOverbars, const EDA_ANGLE &aOrient, const KIFONT::METRICS &aFontMetrics)
Draw overbar lines above text.
virtual void SetViewport(const VECTOR2I &aOffset, double aIusPerDecimil, double aScale, bool aMirror) override
PDF can have multiple pages, so SetPageSettings can be called with the outputFile open (but not insid...
std::map< int, std::pair< BOX2D, std::vector< wxString > > > m_hyperlinkMenuHandles
int m_pageStreamHandle
Handle of the page content object.
virtual void PlotText(const VECTOR2I &aPos, const COLOR4D &aColor, const wxString &aText, const TEXT_ATTRIBUTES &aAttributes, KIFONT::FONT *aFont, const KIFONT::METRICS &aFontMetrics, void *aData=nullptr) override
static std::vector< float > CreateC2WMatrixFromAngles(const VECTOR3D &aTargetPosition, float aCameraDistance, float aYawDegrees, float aPitchDegrees, float aRollDegrees)
Generates the camera to world matrix for use with a 3D View.
std::vector< std::pair< BOX2I, wxString > > m_hyperlinksInPage
List of loaded hyperlinks in current page.
std::unique_ptr< OUTLINE_NODE > m_outlineRoot
Root outline node.
std::vector< std::pair< BOX2I, std::vector< wxString > > > m_hyperlinkMenusInPage
void closePdfObject()
Close the current PDF object.
int m_totalOutlineNodes
Total number of outline nodes.
std::vector< VECTOR2D > arcPath(const VECTOR2D &aCenter, const EDA_ANGLE &aStartAngle, const EDA_ANGLE &aAngle, double aRadius)
const std::string & ResourceName() const
std::string BuildDifferencesArray() const
double FontBBoxMaxY() const
double FontBBoxMinY() const
double UnitsPerEm() const
double FontBBoxMinX() const
void SetToUnicodeHandle(int aHandle)
std::string BuildWidthsArray() const
double FontBBoxMaxX() const
void SetFontHandle(int aHandle)
void SetCharProcsHandle(int aHandle)
std::string BuildToUnicodeCMap() const
std::vector< GLYPH > & Glyphs()
double GetDotMarkLenIU(int aLineWidth) const
Definition plotter.cpp:132
double GetDashGapLenIU(int aLineWidth) const
Definition plotter.cpp:144
const PROJECT * m_project
Definition plotter.h:765
wxString m_subject
Definition plotter.h:757
bool m_mirrorIsHorizontal
Definition plotter.h:740
PAGE_INFO m_pageInfo
Definition plotter.h:758
bool m_plotMirror
Definition plotter.h:738
static const int USE_DEFAULT_LINE_WIDTH
Definition plotter.h:142
void MoveTo(const VECTOR2I &pos)
Definition plotter.h:325
void FinishTo(const VECTOR2I &pos)
Definition plotter.h:335
wxString m_author
Definition plotter.h:756
double m_iuPerDeviceUnit
Definition plotter.h:735
VECTOR2I m_plotOffset
Definition plotter.h:737
VECTOR2I m_penLastpos
Definition plotter.h:751
virtual VECTOR2D userToDeviceCoordinates(const VECTOR2I &aCoordinate)
Modify coordinates according to the orientation, scale factor, and offsets trace.
Definition plotter.cpp:91
VECTOR2I m_paperSize
Definition plotter.h:759
virtual VECTOR2D userToDeviceSize(const VECTOR2I &size)
Modify size according to the plotter scale factors (VECTOR2I version, returns a VECTOR2D).
Definition plotter.cpp:116
char m_penState
Definition plotter.h:750
wxString m_creator
Definition plotter.h:753
int m_currentPenWidth
Definition plotter.h:749
double m_plotScale
Plot scale - chosen by the user (even implicitly with 'fit in a4')
Definition plotter.h:727
FILE * m_outputFile
Output file.
Definition plotter.h:744
void LineTo(const VECTOR2I &pos)
Definition plotter.h:330
void PenFinish()
Definition plotter.h:341
static const int DO_NOT_SET_LINE_WIDTH
Definition plotter.h:141
RENDER_SETTINGS * m_renderSettings
Definition plotter.h:763
virtual void Text(const VECTOR2I &aPos, const COLOR4D &aColor, const wxString &aText, const EDA_ANGLE &aOrient, const VECTOR2I &aSize, enum GR_TEXT_H_ALIGN_T aH_justify, enum GR_TEXT_V_ALIGN_T aV_justify, int aPenWidth, bool aItalic, bool aBold, bool aMultilineAllowed, KIFONT::FONT *aFont, const KIFONT::METRICS &aFontMetrics, void *aData=nullptr)
Draw text with the plotter.
Definition plotter.cpp:548
double m_IUsPerDecimil
Definition plotter.h:733
wxString m_title
Definition plotter.h:755
virtual int GetCurrentLineWidth() const
Definition plotter.h:184
bool m_colorMode
Definition plotter.h:747
double GetDashMarkLenIU(int aLineWidth) const
Definition plotter.cpp:138
wxString m_filename
Definition plotter.h:754
virtual void SetColor(const COLOR4D &color) override
The SetColor implementation is split with the subclasses: the PSLIKE computes the rgb values,...
double plotScaleAdjX
Fine user scale adjust ( = 1.0 if no correction)
void computeTextParameters(const VECTOR2I &aPos, const wxString &aText, const EDA_ANGLE &aOrient, const VECTOR2I &aSize, bool aMirror, enum GR_TEXT_H_ALIGN_T aH_justify, enum GR_TEXT_V_ALIGN_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.
Definition seg.h:38
VECTOR2I A
Definition seg.h:45
VECTOR2I B
Definition seg.h:46
EDA_ANGLE GetCentralAngle() const
Get the "central angle" of the arc - this is the angle at the point of the "pie slice".
double GetRadius() const
EDA_ANGLE GetStartAngle() const
const VECTOR2I & GetCenter() const
Represent a polyline containing arcs as well as line segments: A chain of connected line and/or arc s...
const SHAPE_ARC & Arc(size_t aArc) const
ssize_t ArcIndex(size_t aSegment) const
Return the arc index for the given segment index.
SEG Segment(int aIndex) const
Return a copy of the aIndex-th segment in the line chain.
int SegmentCount() const
Return the number of segments in this line chain.
bool IsArcSegment(size_t aSegment) const
EDA_ORIENTATION m_Angle
GR_TEXT_H_ALIGN_T m_Halign
GR_TEXT_V_ALIGN_T m_Valign
An 8 bit string that is assuredly encoded in UTF8, and supplies special conversion support to and fro...
Definition utf8.h:67
std::string substr(size_t pos=0, size_t len=npos) const
Definition utf8.h:201
const wxString ResolveUriByEnvVars(const wxString &aUri, const PROJECT *aProject)
Replace any environment and/or text variables in URIs.
Definition common.cpp:790
#define _(s)
static constexpr EDA_ANGLE ANGLE_0
Definition eda_angle.h:472
@ DEGREES_T
Definition eda_angle.h:30
FILL_T
Definition eda_fill.h:29
@ NO_FILL
Definition eda_fill.h:30
@ FILLED_SHAPE
Fill with object color.
Definition eda_fill.h:31
@ BOLD
Definition font.h:43
@ SUBSCRIPT
Definition font.h:45
@ ITALIC
Definition font.h:44
@ SUPERSCRIPT
Definition font.h:46
unsigned int TEXT_STYLE_FLAGS
Definition font.h:61
static constexpr double ITALIC_TILT
Tilt factor for italic style (this is the scaling factor on dY relative coordinates to give a tilted ...
Definition font.h:58
int GetPenSizeForBold(int aTextSize)
Definition gr_text.cpp:34
double m_PDFStrokeFontXOffset
Horizontal offset factor applied to stroke font glyph coordinates (in EM units) after to compensate m...
double m_PDFStrokeFontYOffset
Vertical offset factor applied to stroke font glyph coordinates (in EM units) after Y inversion to co...
const wxChar *const tracePdfPlotter
Flag to enable PDF plotter debug tracing.
void ignore_unused(const T &)
Definition ignore.h:20
This file contains miscellaneous commonly used macros and functions.
EDA_ANGLE abs(const EDA_ANGLE &aAngle)
Definition eda_angle.h:461
std::string FormatPdfUtf16Hex(uint32_t aCodepoint)
Format one Unicode code point as the hex digits of its UTF-16BE representation.
Plotting engines similar to ps (PostScript, Gerber, svg)
const int scale
wxString NormalizeFileUri(const wxString &aFileUri)
Normalize file path aFileUri to URI convention.
wxString EscapeString(const wxString &aSource, ESCAPE_CONTEXT aContext)
The Escape/Unescape routines use HTML-entity-reference-style encoding to handle characters which are:...
#define TO_UTF8(wxstring)
Convert a wxString to a UTF8 encoded C string for all wxWidgets build modes.
@ CTX_JS_STR
LINE_STYLE
Dashed line types.
bool isOverbar() const
bool isSuperscript() const
wxString asWxString() const
bool isSubscript() const
wxString title
Title of outline node.
std::vector< OUTLINE_NODE * > children
Ordered list of children.
int entryHandle
Allocated handle for this outline entry.
OUTLINE_NODE * AddChild(int aActionHandle, const wxString &aTitle, int aEntryHandle)
int actionHandle
Handle to action.
static EDA_ANGLE deg(double d)
std::string path
int radius
VECTOR2I end
wxString result
Test unit parsing edge cases and error handling.
int delta
GR_TEXT_H_ALIGN_T
This is API surface mapped to common.types.HorizontalAlignment.
@ GR_TEXT_H_ALIGN_CENTER
@ GR_TEXT_H_ALIGN_RIGHT
@ GR_TEXT_H_ALIGN_LEFT
GR_TEXT_V_ALIGN_T
This is API surface mapped to common.types.VertialAlignment.
@ GR_TEXT_V_ALIGN_BOTTOM
@ GR_TEXT_V_ALIGN_CENTER
@ GR_TEXT_V_ALIGN_TOP
#define M_PI
wxLogTrace helper definitions.
void RotatePoint(int *pX, int *pY, const EDA_ANGLE &aAngle)
Calculate the new point of coord coord pX, pY, for a rotation center 0, 0.
Definition trigo.cpp:227
VECTOR2< int32_t > VECTOR2I
Definition vector2d.h:708
VECTOR2< double > VECTOR2D
Definition vector2d.h:707
VECTOR3< double > VECTOR3D
Definition vector3.h:230
static PIECE rect(double aLeft, double aTop, double aRight, double aBottom, bool aMixed=false)