Fix anchor (#459)

* fix: textbox

* fix

* fix

* fix

* fix

* fix

* fix
main
bokuweb 2022-03-29 17:56:49 +09:00 committed by GitHub
parent 6f787af9af
commit 0af4da71b8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
16 changed files with 1289 additions and 38 deletions

View File

@ -5,6 +5,11 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## docx-rs@0.4.0, docx-wasm@0.0.252 (29. March, 2022)
- [Breaking] Change image size unit `px` to `emu`.
- [Breaking] fix `drawing` json types.
## docx-wasm@0.0.249 (25. March, 2022) ## docx-wasm@0.0.249 (25. March, 2022)
- Change `widthType` case to camelCase in JS. - Change `widthType` case to camelCase in JS.

2
Cargo.lock generated
View File

@ -180,7 +180,7 @@ checksum = "0e25ea47919b1560c4e3b7fe0aaab9becf5b84a10325ddf7db0f0ba5e1026499"
[[package]] [[package]]
name = "docx-rs" name = "docx-rs"
version = "0.3.4" version = "0.4.0"
dependencies = [ dependencies = [
"base64", "base64",
"image", "image",

View File

@ -1,6 +1,6 @@
[package] [package]
name = "docx-rs" name = "docx-rs"
version = "0.3.4" version = "0.4.0"
authors = ["bokuweb <bokuweb12@gmail.com>"] authors = ["bokuweb <bokuweb12@gmail.com>"]
repository = "https://github.com/bokuweb/docx-rs" repository = "https://github.com/bokuweb/docx-rs"
edition = "2018" edition = "2018"

View File

@ -5,34 +5,16 @@ use crate::documents::BuildXML;
use crate::types::*; use crate::types::*;
use crate::xml_builder::*; use crate::xml_builder::*;
#[derive(Debug, Clone, PartialEq, Default)] #[derive(Debug, Clone, PartialEq, Default, Serialize)]
pub struct Drawing { pub struct Drawing {
#[serde(flatten)]
pub data: Option<DrawingData>, pub data: Option<DrawingData>,
} }
impl Serialize for Drawing {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match self.data {
Some(DrawingData::Pic(ref pic)) => {
let mut t = serializer.serialize_struct("Drawing", 2)?;
t.serialize_field("type", "pic")?;
t.serialize_field("data", pic)?;
t.end()
}
_ => {
let t = serializer.serialize_struct("Drawing", 2)?;
t.end()
}
}
}
}
#[derive(Debug, Clone, PartialEq)] #[derive(Debug, Clone, PartialEq)]
pub enum DrawingData { pub enum DrawingData {
Pic(Pic), Pic(Pic),
TextBox(TextBox),
} }
impl Serialize for DrawingData { impl Serialize for DrawingData {
@ -47,6 +29,12 @@ impl Serialize for DrawingData {
t.serialize_field("data", pic)?; t.serialize_field("data", pic)?;
t.end() t.end()
} }
DrawingData::TextBox(ref text_box) => {
let mut t = serializer.serialize_struct("TextBox", 2)?;
t.serialize_field("type", "textBox")?;
t.serialize_field("data", text_box)?;
t.end()
}
} }
} }
} }
@ -60,6 +48,11 @@ impl Drawing {
self.data = Some(DrawingData::Pic(pic)); self.data = Some(DrawingData::Pic(pic));
self self
} }
pub fn text_box(mut self, t: TextBox) -> Drawing {
self.data = Some(DrawingData::TextBox(t));
self
}
} }
impl BuildXML for Box<Drawing> { impl BuildXML for Box<Drawing> {
@ -130,6 +123,7 @@ impl BuildXML for Box<Drawing> {
.close() .close()
.close(); .close();
} }
Some(DrawingData::TextBox(_t)) => unimplemented!("TODO: Support textBox writer"),
None => { None => {
unimplemented!() unimplemented!()
} }

View File

@ -9,7 +9,6 @@ mod bookmark_start;
mod br; mod br;
mod character_spacing; mod character_spacing;
mod color; mod color;
mod run_style;
mod comment; mod comment;
mod comment_extended; mod comment_extended;
mod comment_range_end; mod comment_range_end;
@ -68,6 +67,7 @@ mod run;
mod run_fonts; mod run_fonts;
mod run_property; mod run_property;
mod run_property_default; mod run_property_default;
mod run_style;
mod section; mod section;
mod section_property; mod section_property;
mod shading; mod shading;
@ -98,6 +98,7 @@ mod table_style;
mod table_width; mod table_width;
mod text; mod text;
mod text_border; mod text_border;
mod text_box;
mod text_box_content; mod text_box_content;
mod text_direction; mod text_direction;
mod underline; mod underline;
@ -137,7 +138,6 @@ pub use doc_var::*;
pub use drawing::*; pub use drawing::*;
pub use fld_char::*; pub use fld_char::*;
pub use font::*; pub use font::*;
pub use run_style::*;
pub use font_scheme::*; pub use font_scheme::*;
pub use footer_reference::*; pub use footer_reference::*;
pub use grid_span::*; pub use grid_span::*;
@ -180,6 +180,7 @@ pub use run::*;
pub use run_fonts::*; pub use run_fonts::*;
pub use run_property::*; pub use run_property::*;
pub use run_property_default::*; pub use run_property_default::*;
pub use run_style::*;
pub use section::*; pub use section::*;
pub use section_property::*; pub use section_property::*;
pub use shading::*; pub use shading::*;
@ -210,6 +211,7 @@ pub use table_style::*;
pub use table_width::*; pub use table_width::*;
pub use text::*; pub use text::*;
pub use text_border::*; pub use text_border::*;
pub use text_box::*;
pub use text_box_content::*; pub use text_box_content::*;
pub use text_direction::*; pub use text_direction::*;
pub use underline::*; pub use underline::*;

View File

@ -0,0 +1,178 @@
use serde::Serialize;
use crate::documents::*;
use crate::types::*;
#[derive(Debug, Clone, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct TextBox {
// For writer only
pub children: Vec<TextBoxContentChild>,
// unit is emu
pub size: (u32, u32),
pub position_type: DrawingPositionType,
/// Specifies that this object shall be positioned using the positioning information in the
/// simplePos child element (§20.4.2.13). This positioning, when specified, positions the
/// object on the page by placing its top left point at the x-y coordinates specified by that
/// element.
pub simple_pos: bool,
// unit is emu
pub simple_pos_x: i32,
pub simple_pos_y: i32,
/// Specifies how this DrawingML object behaves when its anchor is located in a table cell;
/// and its specified position would cause it to intersect with a table cell displayed in the
/// document. That behavior shall be as follows:
pub layout_in_cell: bool,
/// Specifies the relative Z-ordering of all DrawingML objects in this document. Each floating
/// DrawingML object shall have a Z-ordering value, which determines which object is
/// displayed when any two objects intersect. Higher values shall indicate higher Z-order;
/// lower values shall indicate lower Z-order.
pub relative_height: u32,
pub allow_overlap: bool,
pub position_h: DrawingPosition,
pub position_v: DrawingPosition,
pub relative_from_h: RelativeFromHType,
pub relative_from_v: RelativeFromVType,
/// Specifies the minimum distance which shall be maintained between the top edge of this drawing object and any subsequent text within the document when this graphical object is displayed within the document's contents.,
/// The distance shall be measured in EMUs (English Metric Units).,
pub dist_t: i32,
pub dist_b: i32,
pub dist_l: i32,
pub dist_r: i32,
}
impl Default for TextBox {
fn default() -> Self {
Self::new()
}
}
impl TextBox {
pub fn new() -> Self {
Self {
children: vec![],
size: (from_px(100), from_px(100)),
position_type: DrawingPositionType::Inline,
simple_pos: false,
simple_pos_x: 0,
simple_pos_y: 0,
layout_in_cell: false,
relative_height: 190500,
allow_overlap: false,
position_v: DrawingPosition::Offset(0),
position_h: DrawingPosition::Offset(0),
relative_from_h: RelativeFromHType::default(),
relative_from_v: RelativeFromVType::default(),
dist_t: 0,
dist_b: 0,
dist_l: 0,
dist_r: 0,
}
}
// unit is emu
pub fn size(mut self, w_emu: u32, h_emu: u32) -> Self {
self.size = (w_emu, h_emu);
self
}
pub fn floating(mut self) -> Self {
self.position_type = DrawingPositionType::Anchor;
self
}
pub fn offset_x(mut self, x: i32) -> Self {
self.position_h = DrawingPosition::Offset(x);
self
}
pub fn offset_y(mut self, y: i32) -> Self {
self.position_v = DrawingPosition::Offset(y);
self
}
pub fn position_h(mut self, pos: DrawingPosition) -> Self {
self.position_h = pos;
self
}
pub fn position_v(mut self, pos: DrawingPosition) -> Self {
self.position_v = pos;
self
}
pub fn relative_from_h(mut self, t: RelativeFromHType) -> Self {
self.relative_from_h = t;
self
}
pub fn relative_from_v(mut self, t: RelativeFromVType) -> Self {
self.relative_from_v = t;
self
}
pub fn dist_t(mut self, v: i32) -> Self {
self.dist_t = v;
self
}
pub fn dist_b(mut self, v: i32) -> Self {
self.dist_b = v;
self
}
pub fn dist_l(mut self, v: i32) -> Self {
self.dist_l = v;
self
}
pub fn dist_r(mut self, v: i32) -> Self {
self.dist_r = v;
self
}
pub fn simple_pos(mut self, v: bool) -> Self {
self.simple_pos = v;
self
}
pub fn relative_height(mut self, v: u32) -> Self {
self.relative_height = v;
self
}
}
/*
impl BuildXML for Textbox {
fn build(&self) -> Vec<u8> {
let b = XMLBuilder::new();
let w = format!("{}", self.size.0);
let h = format!("{}", self.size.1);
b.open_pic("http://schemas.openxmlformats.org/drawingml/2006/picture")
.open_pic_nv_pic_pr()
.pic_c_nv_pr("0", "")
.open_pic_c_nv_pic_pr()
.a_pic_locks("1", "1")
.close()
.close()
.open_blip_fill()
.a_blip(&self.id)
.a_src_rect()
.open_a_stretch()
.a_fill_rect()
.close()
.close()
.open_pic_sp_pr("auto")
.open_a_xfrm()
.a_off("0", "0")
.a_ext(&w, &h)
.close()
.open_a_prst_geom("rect")
.a_av_lst()
.close()
.close()
.close()
.build()
}
}
*/

View File

@ -13,8 +13,8 @@ pub struct TextBoxContent {
#[derive(Debug, Clone, PartialEq)] #[derive(Debug, Clone, PartialEq)]
pub enum TextBoxContentChild { pub enum TextBoxContentChild {
Paragraph(Paragraph), Paragraph(Box<Paragraph>),
Table(Table), Table(Box<Table>),
} }
impl Serialize for TextBoxContentChild { impl Serialize for TextBoxContentChild {
@ -48,7 +48,8 @@ impl TextBoxContent {
if p.has_numbering { if p.has_numbering {
self.has_numbering = true self.has_numbering = true
} }
self.children.push(TextBoxContentChild::Paragraph(p)); self.children
.push(TextBoxContentChild::Paragraph(Box::new(p)));
self self
} }
@ -56,7 +57,7 @@ impl TextBoxContent {
if t.has_numbering { if t.has_numbering {
self.has_numbering = true self.has_numbering = true
} }
self.children.push(TextBoxContentChild::Table(t)); self.children.push(TextBoxContentChild::Table(Box::new(t)));
self self
} }
} }

View File

@ -75,6 +75,44 @@ fn read_position_v<R: Read>(
} }
} }
fn read_textbox_content<R: Read>(
r: &mut EventReader<R>,
_attrs: &[OwnedAttribute],
) -> Result<Vec<TextBoxContentChild>, ReaderError> {
let mut children = vec![];
loop {
let e = r.next();
match e {
Ok(XmlEvent::StartElement {
attributes, name, ..
}) => {
let e = XMLElement::from_str(&name.local_name).unwrap();
match e {
XMLElement::Paragraph => {
let p = Paragraph::read(r, &attributes)?;
children.push(TextBoxContentChild::Paragraph(Box::new(p)));
continue;
}
XMLElement::Table => {
let t = Table::read(r, &attributes)?;
children.push(TextBoxContentChild::Table(Box::new(t)));
continue;
}
_ => {}
}
}
Ok(XmlEvent::EndElement { name, .. }) => {
let e = WpsXMLElement::from_str(&name.local_name).unwrap();
if e == WpsXMLElement::Txbx {
return Ok(children);
}
}
Err(_) => return Err(ReaderError::XMLReadError),
_ => {}
}
}
}
impl ElementReader for Drawing { impl ElementReader for Drawing {
fn read<R: Read>( fn read<R: Read>(
r: &mut EventReader<R>, r: &mut EventReader<R>,
@ -222,6 +260,31 @@ impl ElementReader for Drawing {
drawing = drawing.pic(pic); drawing = drawing.pic(pic);
} }
} }
// wps:
if let Ok(WpsXMLElement::Txbx) = WpsXMLElement::from_str(&name.local_name) {
if let Ok(children) = read_textbox_content(r, &attributes) {
let mut text_box = TextBox::new();
text_box.position_type = drawing_position_type;
text_box.simple_pos = simple_pos;
text_box.simple_pos_x = simple_pos_x;
text_box.simple_pos_y = simple_pos_y;
text_box.layout_in_cell = layout_in_cell;
text_box.relative_height = relative_height;
text_box.allow_overlap = allow_overlap;
text_box.dist_r = dist_r;
text_box.dist_t = dist_t;
text_box.dist_b = dist_b;
text_box.dist_l = dist_l;
text_box.dist_r = dist_r;
text_box.relative_from_h = relative_from_h;
text_box.relative_from_v = relative_from_v;
text_box.position_v = DrawingPosition::Offset(position_v);
text_box.position_h = DrawingPosition::Offset(position_h);
text_box.children = children;
drawing = drawing.text_box(text_box);
}
}
} }
Ok(XmlEvent::EndElement { name, .. }) => { Ok(XmlEvent::EndElement { name, .. }) => {
let e = XMLElement::from_str(&name.local_name).unwrap(); let e = XMLElement::from_str(&name.local_name).unwrap();

View File

@ -100,7 +100,6 @@ const COMMENTS_EXTENDED_TYPE: &str =
"http://schemas.microsoft.com/office/2011/relationships/commentsExtended"; "http://schemas.microsoft.com/office/2011/relationships/commentsExtended";
fn read_headers( fn read_headers(
rels: &ReadDocumentRels, rels: &ReadDocumentRels,
archive: &mut ZipArchive<Cursor<&[u8]>>, archive: &mut ZipArchive<Cursor<&[u8]>>,
) -> HashMap<RId, Header> { ) -> HashMap<RId, Header> {
@ -411,7 +410,7 @@ pub fn read_docx(buf: &[u8]) -> Result<Docx, ReaderError> {
// Read media // Read media
let media = rels.find_target_path(IMAGE_TYPE); let media = rels.find_target_path(IMAGE_TYPE);
if let Some(paths) = media { if let Some(paths) = media {
if let Some((_, media)) = paths.get(0) { for (_, media) in paths {
let data = read_zip(&mut archive, media.to_str().expect("should have media"))?; let data = read_zip(&mut archive, media.to_str().expect("should have media"))?;
docx = docx.add_image(data); docx = docx.add_image(data);
} }

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -1,10 +1,24 @@
import { TextBoxContentJSON } from "./textbox-content"; import { TextBoxContentJSON } from "./textbox-content";
import { Pic as InnerPic } from "./bindings/Pic";
import { ParagraphJSON, TableJSON } from "..";
export interface Pic extends Omit<InnerPic, "image"> {
image: string;
}
export type DrawingJSON = { export type DrawingJSON = {
type: "drawing"; type: "drawing";
data: { data:
type: "pic"; | {
}; type: "pic";
data: Pic;
}
| {
type: "textBox";
data: {
children: (ParagraphJSON | TableJSON)[];
};
};
}; };
export type WpAnchorJSON = { export type WpAnchorJSON = {

View File

@ -1,6 +1,6 @@
{ {
"name": "docx-wasm", "name": "docx-wasm",
"version": "0.0.250", "version": "0.0.252",
"main": "dist/node/index.js", "main": "dist/node/index.js",
"browser": "dist/web/index.js", "browser": "dist/web/index.js",
"author": "bokuweb <bokuweb12@gmail.com>", "author": "bokuweb <bokuweb12@gmail.com>",

File diff suppressed because one or more lines are too long

View File

@ -130,6 +130,12 @@ describe("reader", () => {
const json = w.readDocx(buffer); const json = w.readDocx(buffer);
expect(json).toMatchSnapshot(); expect(json).toMatchSnapshot();
}); });
test("should read textbox", () => {
const buffer = readFileSync("../fixtures/textbox/textbox.docx");
const json = w.readDocx(buffer);
expect(json).toMatchSnapshot();
});
}); });
describe("writer", () => { describe("writer", () => {

BIN
image.docx 100644

Binary file not shown.