封装代码,如下:
import scala.scalajs.js
import scala.scalajs.js.annotation._
package object pdfJS {
import org.scalajs.dom.CanvasRenderingContext2D
@JSGlobal("PDFJS")
@js.native
object PDFJS extends js.Object {
var workerSrc: String = js.native
def getDocument(url: String): PDFDocumentLoadingTask = js.native
}
@js.native
class PageViewport extends js.Object {
val height: Double= js.native
val width: Double = js.native
}
@js.native
class PDFPageProxy extends js.Object {
def getViewport(scale: Double): PageViewport = js.native
def render(params: js.Object): js.Promise[RenderTask] = js.native
}
@ScalaJSDefined
trait RenderContext extends js.Object {
val canvasContext: CanvasRenderingContext2D
val viewport: PageViewport
}
@js.native
class RenderTask extends js.Object {
}
@js.native
class PDFDocumentProxy extends js.Object {
def getPage(pageNumber: Int ): js.Promise[PDFPageProxy] = js.native
val numPages: Int = js.native
}
@js.native
class PDFDocumentLoadingTask extends js.Object {
def promise: js.Promise[PDFDocumentProxy] = js.native
def onProgress:js.Object=js.native
}
}
这只是封装了一部分代码,还有好多东西由于没有用到就没有封装进去。目前PDFDocumentLoadingTask 中的onProgress的值一直为null 还没有理解,别的都可以正常使用。
下面是使用的代码:
object DrawPDF {
def draw(area: HTMLElement, url: String) = {
//1.8.618
PDFJS.workerSrc = "/zhishiku/static/js/pdf.worker.min.js"
val loadingTask = PDFJS.getDocument(url)
println(JSON.stringify(loadingTask))
println(loadingTask.onProgress)
loadingTask.promise.toFuture.map {
rsp =>
area.textContent = ""
println(url + "PDF loaded")
for (i <- 1 to rsp.numPages) {
rsp.getPage(i).toFuture.onComplete {
case Success(rsp1) =>
println("Page loaded")
val viewportDiv = rsp1.getViewport(1.5)
val pdfArea = canvas("Your browser does not support the canvas element.").render
area.appendChild(pdfArea)
val context = pdfArea.getContext("2d").asInstanceOf[CanvasRenderingContext2D]
pdfArea.height = viewportDiv.height.toInt+1
pdfArea.width = viewportDiv.width.toInt+1
val renderContext = new RenderContext {
override val canvasContext = context
override val viewport = viewportDiv
}
println(renderContext)
println("2")
val renderTask =
try {
rsp1.render(renderContext)
}
catch {
case error: Exception =>
error.printStackTrace()
throw error
}
renderTask.toFuture.onComplete {
case Success(rsp2) =>
println("Page rendered")
case Failure(error) =>
println("rsp.render" + error)
}
case Failure(error) =>
println("rsp.getPage()" + error)
}
}
}
}
}
网友评论