Wikipedia:WikiProject Chemistry/Structure drawing workgroup/Mysid's script: Difference between revisions

Content deleted Content added
Remove cropping code (better to do it in BKchem)
change source to syntaxhighlight
 
(9 intermediate revisions by 5 users not shown)
Line 1:
<sourcesyntaxhighlight lang="perl">
#!/usr/bin/perl -i.old
#Modify svg file from BKchem to work with librsvg, for use on Wikimedia.
use Image::Magick;
 
# original source: https://en.wikipedia.org/wiki/Wikipedia:WikiProject_Chemistry/Structure_drawing_workgroup/Mysid%27s_script
#Does the input file exist?
if(! -f $ARGV[0])
{print "$ARGV[0]: File not found\n";
exit};
#Open files. TODO: check that output file is writeable.
open INPUT,"<$ARGV[0]";
$outfile1 = $ARGV[0];
$outfile1 =~ s/.svg/1.svg/;
open OUTPUT,">$outfile1";
 
# Note: "-i.old" means original file will be renamed to <filename>.old
while (<INPUT>) {
# Modify svg file from BKchem to work with librsvg, for use on Wikimedia.
#I must skip over "defs" blocks, because they have objects with relative
 
#dimensions. TODO:This is nasty code. I'm sure there's a better way to do
use warnings;
#this.
use strict;
if (/defs/) {
 
print OUTPUT $_;
my $line font_size = $_24;
 
while (!($line =~ /\/defs/)){
while (<INPUT>) {
$line = <INPUT>;
print OUTPUT $line;
}
next;
}
#Sans is the most general font definition we can use, and librsvg chokes
#on Helvetica.
s/helvetica/Sans/gi;
if(m#<text[^>]+font-size="([0-9]+)pt"#){
if (!/viewBox/ && /\d/) {
$font_size = $1;
#Round the numbers.
}
s/(\d+\.\d+)/sprintf("%.1f", $&)/ge unless(/version/);
#and fixConvert relative font sizes forto super-absolute andfont subscriptssizes
s#(font-size=")([0-9]+)%(")#$1.($2*$font_size/100)."pt".$3#ge;
s/75\%/9pt/g;
}
# Replace baseline-shift="super" with a numeric baseline-shift
if (/y="([\d\.]+)">.*<tspan baseline-shift="super"/) {
my $vy = $1;
my $oy = $1-4;
s/baseline-shift="super"/y="$oy"/g;
s/#<\/tspan>([^<]+)</#<\/tspan><tspan y="$vy">$1<\/tspan></#g;
}
# Replace baseline-shift="sub" with a numeric baseline-shift
if (/y="([\d\.]+)">.*<tspan baseline-shift="sub"/) {
my $vy = $1;
my $oy = $1+3.25;
s/baseline-shift="sub"/y="$oy"/g;
s/#<\/tspan>([^<]+)</#<\/tspan><tspan y="$vy">$1<\/tspan></#g;
}
#write each line out after mangling it.
print OUTPUT $_;
}
#close the files (done with the original input file, output file becomes
#input for next pass.
close OUTPUT;
close INPUT;
 
 
open INPUT,"<$outfile1";
$outfile2 = $ARGV[0];
$outfile2 =~ s/.svg/2.svg/;
open OUTPUT,">$outfile2";
while (<INPUT>) {
#Take out redundant groups.
if (/<\/g>/) {
my $line = $_;
$nextline = <INPUT>;
if (!($nextline =~ /<g stroke="\#000000" stroke-width="[\d.]+">\s/ )) {
print OUTPUT $line;
print OUTPUT $nextline;
}
} else {
print OUTPUT $_;}
}
</syntaxhighlight>
#clean up
close OUTPUT;
close INPUT;
unlink("$outfile1");
print "$outfile2 written\n";
</source>