Articles in this section

How to Rotate All PDF Pages with a Single Click in Angular PDF Viewer?

Description:

This article explains how to rotate all pages of a PDF document with a single click in the Syncfusion® PDF Viewer component within an Angular PDF Viewer application. By following this guide, users can implement custom toolbar buttons to rotate pages clockwise or counterclockwise, enhancing document viewing flexibility.

Solution:

To rotate all pages in the PDF Viewer, use custom toolbar items and handle their click events. The rotation is achieved by saving the current PDF as a blob, modifying each page’s rotation angle, and reloading the updated document.

Prerequisites:

Before diving into the implementation, ensure that the following steps are completed:

  1. Syncfusion PDF Viewer Setup: Make sure the Syncfusion PDF Viewer is installed and set up in your Angular project. Follow the Getting Started with Syncfusion PDF Viewer for Angular guide if you haven’t already.

  2. Basic Knowledge of Angular: Familiarity with Angular components and the basic setup of Angular projects will help you follow along with the implementation.

Code Snippets
Set Up PDF Viewer with Custom Toolbar
app.component.html
<style>
  .control-section{
      margin-top: 100px;
  }
</style>
<div class="control-section">
    <ejs-pdfviewer
      #pdfviewer
      id="pdfViewer"
      [documentPath]="document"
      [resourceUrl]="resource"
      [toolbarSettings]="toolbarSettings"
      (toolbarClick)="toolbarClick($event)"
      style="height:640px;display:block"
    ></ejs-pdfviewer>
</div>
Component Logic for Page Rotation
app.component.ts
import { Component, ViewEncapsulation, OnInit, ViewChild } from '@angular/core';
import {
  PdfViewerComponent,
  LinkAnnotationService,
  BookmarkViewService,
  MagnificationService,
  ThumbnailViewService,
  ToolbarService,
  NavigationService,
  TextSearchService,
  TextSelectionService,
  PrintService,
  AnnotationService,
  FormFieldsService,
  FormDesignerService,
  PageOrganizerService,
  PdfViewerModule,
} from '@syncfusion/ej2-angular-pdfviewer';
import { SwitchComponent, SwitchModule } from '@syncfusion/ej2-angular-buttons';
import { ClickEventArgs } from '@syncfusion/ej2-buttons';
import { CustomToolbarItemModel } from '@syncfusion/ej2-pdfviewer';
import {
    PdfDocument,
    PdfPage,
    PdfRotationAngle,
  } from '@syncfusion/ej2-pdf';
  
/**
 * Default PdfViewer Controller
 */
@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html',
  encapsulation: ViewEncapsulation.None,
  // tslint:disable-next-line:max-line-length
  providers: [
    LinkAnnotationService,
    BookmarkViewService,
    MagnificationService,
    ThumbnailViewService,
    ToolbarService,
    NavigationService,
    TextSearchService,
    TextSelectionService,
    PrintService,
    AnnotationService,
    FormFieldsService,
    FormDesignerService,
    PageOrganizerService,
  ],
  styleUrls: ['app.component.css'],
  standalone: true,
  imports: [SwitchModule, PdfViewerModule],
})
export class AppComponent {
  @ViewChild('pdfviewer')
  public pdfviewerControl: PdfViewerComponent | undefined;
  public currentPageNumber: number | undefined;

  public document: string =
    'https://cdn.syncfusion.com/content/pdf/pdf-succinctly.pdf';
  public resource: string =
    'https://cdn.syncfusion.com/ej2/23.2.6/dist/ej2-pdfviewer-lib';
  ngOnInit(): void {
    // ngOnInit function
  }
  public change(e: any): void {
    if(this.pdfviewerControl){
    if (e.checked) {
      this.pdfviewerControl.serviceUrl = '';
    } else {
      this.pdfviewerControl.serviceUrl =
        'https://services.syncfusion.com/angular/production/api/pdfviewer';
    }
    this.pdfviewerControl.dataBind();
    this.pdfviewerControl.load(this.pdfviewerControl.documentPath, "");
  }
}
// Custom toolbar item for rotating pages counterclockwise
  public toolItem1: CustomToolbarItemModel = {
    prefixIcon: 'e-icons e-transform-left',
    id: 'rotateCounterclockwise',
    tooltipText: 'Custom toolbar item',
  };
  // Custom toolbar item for rotating pages clockwise
  public toolItem2: CustomToolbarItemModel = { 
    prefixIcon: 'e-icons e-transform-right',
    id: 'rotateClockwise',
    tooltipText: 'Custom toolbar item',
  };
  // Toolbar configuration including custom rotation buttons  
  public toolbarSettings = {
    showTooltip: true,
    toolbarItems: [
      this.toolItem1,
      this.toolItem2,
      'OpenOption',
      'PageNavigationTool',
      'MagnificationTool',
      'PanTool',
      'SelectionTool',
      'SearchOption',
      'PrintOption',
      'DownloadOption',
      'UndoRedoTool',
      'AnnotationEditTool',
      'FormDesignerEditTool',
      'CommentTool',
      'SubmitForm',
    ],
  };
  public toolbarClick(args: any): void {
    var pdfViewer = (<any>document.getElementById('pdfViewer'))
      .ej2_instances[0];
      var _this = this;
      // Rotate all pages clockwise
    if (args.item && args.item.id === 'rotateClockwise') {
      this.currentPageNumber = pdfViewer.currentPageNumber - 1;
      pdfViewer.saveAsBlob().then(function (value: Blob) {
        var reader = new FileReader();
        reader.readAsDataURL(value);
        reader.onload = () => {
          var base64 = (reader.result as any).split('base64,')[1];
          let pdfDocument = new PdfDocument(base64);
          for(var i=0; i<pdfViewer.pageCount; i++){
            let page = pdfDocument.getPage(i) as PdfPage;
            var rotation = page.rotation + 1;
            if(rotation > 4){ 
              rotation = 0;
            }
            page.rotation = _this.getPdfRotationAngle(rotation);
          }
          pdfDocument.saveAsBlob().then((value) => {
            var reader = new FileReader();
            reader.readAsDataURL(value.blobData);
            reader.onload = () => {
              var base64data = reader.result; 
              pdfViewer.load(base64data);
            }; 
          });
        };
      });
    }
    // Rotate all pages counterclockwise 
    else if (args.item && args.item.id === 'rotateCounterclockwise') {
      this.currentPageNumber = pdfViewer.currentPageNumber - 1;
      pdfViewer.saveAsBlob().then(function (value: Blob) {
        var reader = new FileReader();
        reader.readAsDataURL(value);
        reader.onload = () => {
          var base64 = (reader.result as any).split('base64,')[1];
          let pdfDocument = new PdfDocument(base64);
          for(var i=0; i<pdfViewer.pageCount; i++){
            let page = pdfDocument.getPage(i) as PdfPage;
            var rotation = page.rotation - 1;
            if(rotation < 0){ 
              rotation = 3;
            }
            page.rotation = _this.getPdfRotationAngle(rotation);
          }
          pdfDocument.saveAsBlob().then((value) => {
            var reader = new FileReader();
            reader.readAsDataURL(value.blobData);
            reader.onload = () => {
              var base64data = reader.result; 
              pdfViewer.load(base64data);
            }; 
          });
        };
      });
    }
  }
  //Converts numeric rotation value to PdfRotationAngle enum.
  private getPdfRotationAngle(rotation: number): PdfRotationAngle {
        switch (rotation) {
            case 0:
                return PdfRotationAngle.angle0;
            case 1:
                return PdfRotationAngle.angle90;
            case 2:
                return PdfRotationAngle.angle180;
            case 3:
                return PdfRotationAngle.angle270;
            default:
                return PdfRotationAngle.angle0;
        }
    }
}
Key Features Used:
  1. CustomToolbarItemModel: Adds custom buttons to the toolbar.
  2. toolbarClick Event: Handles click actions for custom toolbar items.
  3. PdfDocument & PdfPage: Used to manipulate the rotation of each page.
  4. PdfRotationAngle Enum: Defines rotation angles (0°, 90°, 180°, 270°).
Sample Link:

You can find the full sample in our GitHub repository.

Conclusion:

I hope you enjoyed learning how to rotate all PDF pages with a single click in Angular PDF Viewer.

You can refer to Angular PDF Viewer feature tour page to know about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our Angular PDF Viewer Example to understand how to create and manipulate data.

For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls.

If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, BoldDesk Support, or feedback portal. We are always happy to assist you!

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Access denied
Access denied