프린트용 CSS 작업기록

  • Post author:
  • Post category:칼럼
  • Post comments:0 Comments
  • Post last modified:April 7, 2020

블로그에 쓴 초안을 PDF로 프린트하려 했더니 화면이 한쪽에 쏠리고 불필요한 댓글이 출력되는 등 그야말로 엉망진칭이다. Print 용 CSS 적용 완료를 쓸 무렵에는 이런 소소한 부분까지 신경썼더랬다. 그때와 지금은 삶이 다르니 어쩔 수 없겠지.

오랜만에 웹 프론트엔드 작업을 하려니 약간은 걱정이 되었다. 하지만 웹표준이 막 등장하던 시점과 달리 요새는 모든 것이 잘 정리되어 접근하기에 한결 쉬웠다. 특히 프린트용 CSS를 구성할 때 유용한 팁을 잘 정리한 문서가 있어 크게 도움이 되었다.

작업 자체는 크게 어렵지 않고 OceanWP 테마에 맞춰 자잘하게 수정하기를 반복하는데 대부분의 시간을 허비했다. 그래도 결과물에는 만족한다. 완벽하지는 않아도 이 정도면 수고대비 괜찮지 않나 싶다.

코드

워드프레스의 Custom CSS 란에 다음과 같이 프린트용 CSS를 넣었다. 5 Powerful Tips And Tricks For Print Style Sheets를 거의 베끼다시피 했다.

@media print {

   * {
      color: #000;
      background-color: #fff;
      background: none;
      box-shadow: none;
      text-shadow: none;
   }

   /* Expand External Links For Print */

   /* a:after {
      content: "( "attr(href)" )";
   } */

   article a:not(:local-link):after {
      content:" <" attr(href) "> ";
   }

   article .meta a:after {
      content: "";
   }

   header h2 {
      font-size: 40px !important;
      margin-right: 200px !important;
      line-height: 1.6 !important;
      padding: 0 !important;
   }

   header img {
      filter: url(inverse.svg#negative);
      -webkit-filter: invert(100%);
      filter: invert(100%);
   }

   /* Prevent headings from being printed at the bottom of the page: */
   h2, h3 {
      page-break-after: avoid;
   }
   
   /* Another rule will prevent images from bleeding over the edge of the printed page: */
   img {
      max-width: 100% !important;
   }

   /* We can prevent large elements, such as unordered lists and images, from being split across multiple pages. */
   ul, img {
      page-break-inside: avoid;
   }

   nav,
   aside,
   footer {
      display: none;
   }

   #site-header,
   #top-bar-wrap,
   #wpadminbar,
   #author-bio,
   #comments,
   #disqus_thread,
   #jp-relatedposts,
   #scroll-top,
   #sidr,
   #sidr-close,
   #wpstats,
   #bmc,
   #fancybox-wrap {
      display: none;
   }

   .page-header,
   .post-tags,
   .jp-relatedposts,
   .sloc-display,
   .print {
      display: none !important;
   }

   #main,
   #content-wrap,
   #primary,
   #content {
      width: 100%;
      border: 0 !important;
      margin: 0 !important;
      padding: 0 !important;
      float: none !important;
   }

   /* #main::after {
      display: none;
   } */

   .container {
      width: 100%;
      max-width: 100%;
      margin: 0 !important;
      padding: 0 !important;
   }

   article {
      width: 100%;
      border: 0 !important;
      /* margin: 0 5%; */
      margin: 0 !important;
      padding: 0 !important;
      float: none !important;
   }

   @page {
      size: A4;
      margin: 1cm;
      padding: 0;
   }
}

/*
On some websites, such as portfolios, background images and colors are an important visual component. If the user is printing from a WebKit browser (Google’s Chrome or Apple’s Safari), we can force the printer to render the colors as seen on screen (i.e. force any background images and colors to appear on the printed page). Generally speaking, we would do this for color printers, which we can test for in a separate media query
 */
@media print and (color) {
   * {
      -webkit-print-color-adjust: exact;
      print-color-adjust: exact;
   }
}

대체로 어렵지 않았으나 QR 코드를 보여주는 것은 살짝 까다로웠다. CSS에 글의 Permalink를 넣어주려면 아래와 같이 CSS를 동적으로 생성해야 하기 때문이다.

@media print {
   header h1:after {
      content: url(https://chart.googleapis.com/chart?cht=qr&chs=150x150&chl=http://yourdomain.com&choe=UTF-8);
      position: absolute;
      right: 0;
      top: 0;
   }
}

이 문제는 PHP 코드를 임의으로 추가할 수 있는 Woody ad snippets 플러그인을 이용해 쉽게 해결했다. 플러그인을 설치하고 다음과 같은 PHP 코드를 넣었다. 이 스니펫은 Single 글일 때 QR 코드용 CSS를 생성해 추가한다.

/* 
See
- https://www.smashingmagazine.com/2013/03/tips-and-tricks-for-print-style-sheets/
- https://wpscholar.com/blog/dynamic-styling-with-wp_add_inline_style/
- https://wordpress.stackexchange.com/questions/104657/how-to-add-dynamic-inline-style/104659
*/
function add_custom_css() {
    wp_enqueue_style('custom-css', get_template_directory_uri() . '/custom.css');
    // Add dynamic style if a single page is displayed
    if ( is_single() ) {
		$permalink = get_the_permalink();
        $custom_css = "
@media print {
    header h2:after {
        content: url(https://chart.googleapis.com/chart?cht=qr&chs=125x125&chl=https://$permalink&choe=UTF-8);
        position: absolute;
        right: 0;
        top: 0;
    }
}";
        wp_add_inline_style( 'custom-css', $custom_css );
    }
}
add_action( 'wp_enqueue_scripts', 'add_custom_css' );

그 외 참고자료

Author Details
Kubernetes, DevSecOps, AWS, 클라우드 보안, 클라우드 비용관리, SaaS 의 활용과 내재화 등 소프트웨어 개발 전반에 도움이 필요하다면 도움을 요청하세요. 지인이라면 가볍게 도와드리겠습니다. 전문적인 도움이 필요하다면 저의 현업에 방해가 되지 않는 선에서 협의가능합니다.
0 0 votes
Article Rating
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments