Skip to content

Commit

Permalink
Load user style sheet when loading HTML from MuPDF
Browse files Browse the repository at this point in the history
HTML here means all the HTML based formats that MuPDF handles.

Since MuPDF supports @font-face, we can now change the font family
of a rendered `.txt` file with, for example, the following code
in `css/html-user.css`:

```css
@font-face {
	font-family: "Source Code";
	src: url("fonts/SourceCodeVariable-Roman.otf");
}

pre {
	font-family: "Source Code";
}
```

Fixes #358.
  • Loading branch information
baskerville committed Apr 1, 2024
1 parent fad6eb2 commit 6771ea0
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 13 deletions.
5 changes: 4 additions & 1 deletion crates/core/src/document/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -240,7 +240,10 @@ pub fn open<P: AsRef<Path>>(path: P) -> Option<Box<dyn Document>> {
})
},
_ => {
PdfOpener::new().and_then(|o| {
PdfOpener::new().and_then(|mut o| {
if matches!(k.as_ref(), "mobi" | "fb2" | "xps" | "txt") {
o.load_user_stylesheet();
}
o.open(path)
.map(|d| Box::new(d) as Box<dyn Document>)
})
Expand Down
21 changes: 9 additions & 12 deletions crates/core/src/document/pdf.rs
Original file line number Diff line number Diff line change
@@ -1,22 +1,23 @@
use super::mupdf_sys::*;

use std::fs;
use std::ptr;
use std::slice;
use std::char;
use std::rc::Rc;
use std::path::Path;
use std::io::Read;
use std::fs::File;
use std::io::ErrorKind;
use std::ffi::{CString, CStr};
use std::os::unix::ffi::OsStrExt;
use anyhow::Error;
use super::{Document, Location, TextLocation, BoundedText, TocEntry};
use super::{chapter, chapter_relative};
use crate::metadata::TextAlign;
use crate::geom::{Boundary, CycleDir};
use crate::unit::pt_to_px;
use crate::framebuffer::Pixmap;

const USER_STYLESHEET: &str = "css/html-user.css";

impl Into<Boundary> for FzRect {
fn into(self) -> Boundary {
Boundary {
Expand Down Expand Up @@ -92,16 +93,12 @@ impl PdfOpener {
}
}

pub fn set_user_css<P: AsRef<Path>>(&mut self, path: P) -> Result<(), Error> {
let mut file = File::open(path)?;
let mut buf = Vec::new();
file.read_to_end(&mut buf)?;
let buf = CString::new(buf)?;
unsafe {
// The CSS will only be parsed when an HTML or EPUB document is opened
fz_set_user_css((self.0).0, buf.as_ptr());
pub fn load_user_stylesheet(&mut self) {
if let Ok(content) = fs::read_to_string(USER_STYLESHEET)
.and_then(|s| CString::new(s).map_err(Into::into))
.map_err(|e| if e.kind() != ErrorKind::NotFound { eprintln!("{:#}", e) }) {
unsafe { fz_set_user_css((self.0).0, content.as_ptr()) }
}
Ok(())
}
}

Expand Down

0 comments on commit 6771ea0

Please sign in to comment.