I have encountered an issue while using a library called ng2-pdf-viewer. The default way to stick to a page in the PDF document was not working as expected. To overcome this, I utilized jQuery's scrollTo()
method to navigate to the specific .page
class within the PDF. For example, scrolling to page 2 would be represented as .page:nth-child(2)
. While this solution works after refreshing the page, it does not auto-scroll when first landing on the page. At this point, using jQuery scrollTo seems to be the only approach that somewhat resolves the issue.
HTML
<pdf-viewer [src]="pdfSrc"
[render-text]="true"
[autoresize]="true"
[original-size]="false"
style="display: block;" (after-load-complete)="callBackFn($event)">
</pdf-viewer>
COMPONENT.TS
import { Component, OnInit, Output, EventEmitter, AfterViewInit} from '@angular/core';
import { AppConsts } from '@shared/AppConsts';
import { AppComponentBase } from '@shared/common/app-component-base';
import { ActivatedRoute } from '@angular/router';
import { HeaderTitleService } from '@shared/service/headerTitle.service';
declare var jQuery: any;
const $ = jQuery;
@Component({
selector: 'app-pdfview',
templateUrl: './pdfview.component.html',
styleUrls: ['./pdfview.component.less']
})
export class PdfviewComponent implements OnInit {
pdfSrc: string;
pdf: string;
pageNum: number = 2;
botString: string;
pageNumberVar: string;
@Output() notify: EventEmitter<String> = new EventEmitter<String>();
constructor(
private route: ActivatedRoute,
private headerTitleService: HeaderTitleService
) {
this.pdf = route.snapshot.params['pdfId'];
if (this.pdf === '1') {
this.pdfSrc = '../../../assets/pdf/emeds1.pdf';
this.botString = 'Admission Reconciliation loaded on Page 2 - matching the word ‘reconcile’ for you.';
this.pageNumberVar = '2';
} else if (this.pdf === '2') {
this.pdfSrc = '../../../assets/pdf/medrec.pdf';
this.botService.sendMessage('I have loaded the document on page 21 showing "Medication Reconciliation"');
setTimeout(() => {
this.botService.sendMessage('That saved you hours of reading :)');
}, 2000);
setTimeout(() => {
$('html, body').animate({
scrollTop: $('.page:nth-child(29)').offset().top
}, 300);
}, 1000);
}
}
callBackFn(pdf: PDFDocumentProxy) {
this.botService.sendMessage(this.botString);
}
ngAfterViewInit() {
setTimeout(function(){
$('html, body').animate({
scrollTop: $('.page:nth-child(' + this.pageNumberVar + ')').offset().top
}, 300);
}, 1000);
}
}
Even after attempting to incorporate the scrollTo function within ngAfterViewInit
, the auto-scroll issue still persists.